Home > Cordova, Java, PhoneGap > Native tick sound on button click with PhoneGap

Native tick sound on button click with PhoneGap

PhoneGap is a good framework to build hybrid applications, but for a great usability the devil is in the detail. A difference with native buttons is that HTML5 rendered hyper-links don’t produce a click sound with PhoneGap. Such small difference gives directly 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).

Advertisements
Categories: Cordova, Java, PhoneGap
  1. May 22, 2014 at 18:34

    Good job, you could provide the full code on github?

  2. MightyGoat
    July 1, 2014 at 17:13

    where do I have to paste the Java Code in?

  3. Andrea
    August 13, 2014 at 18:20

    I haven’t understand where do i have put the java code. can you help me, please?

  4. Elroy
    January 30, 2016 at 13:36

    Where Do i put the java code? I’m using VS Tools for cordova

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: