Mobile Zone is brought to you in partnership with:

My name is Pieter De Rycke, I am a Belgian technical .Net architect working in the insurance sector. I am always eager to learn new technologies and I like to keep up with the latest innovations and trends in the IT sector. I am a big believer in web services for interoperability between platforms. Pieter is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

How to Create the Native Tick Sound on Button Click with PhoneGap

02.20.2014
| 3420 views |
  • submit to reddit

PhoneGap is a good framework to build hybrid applications, but for great usability the devil is in the details. A difference with native buttons is that HTML5 rendered hyper-links don’t produce a click sound with PhoneGap. Such small difference gives a non-standard user experience to your app. So I came up with a small PhoneGap plug-in to fix this small annoyance.

Java code:

public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if("click".equals(action)) {
        try {
            cordova.getActivity().runOnUiThread(new Runnable(){
                public void run(){
                    try {
                        View view = cordova.getActivity().getWindow().getDecorView();
                        view.playSoundEffect(SoundEffectConstants.CLICK);
                    }
                    catch(Exception ex) {
                        callbackContext.error(ex.getMessage());
                    }
                }
            });
        }
        catch(Exception ex) {
            callbackContext.error(ex.getMessage());
        }
 
        return true;
    }
 
    return false;
}

JavaScript code:

$(function() {
    $(document).on("click", ".sound-click", function() {
        cordova.exec(function () { },
                    function () { },
                    "SoundEffects",
                    "click",
                    []);
    });
});

In order to have the click sound, it it sufficient to add the “sound-click” class to your HTML5 buttons (and jQuery referenced in your page).


Published at DZone with permission of Pieter De Rycke, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)