benoffi7
benoffi7

Reputation: 3106

Handle audiojack button

I I bought this Key Quick Button Pressy Dustproof Plug Earphone Jack Plug and I would like develop apps for this.

How can I handle the click as a service or broadcast in Android so run some logic on click?

This android official blog not working. I'm using 4.0+

This is my code

Thanks!

Upvotes: 3

Views: 219

Answers (1)

Mike M.
Mike M.

Reputation: 39201

That would be what's called a Media Button, and it does cause a system broadcast that can be handled by a BroadcastReceiver, but it needs to be implemented a little differently than regular Receivers. Only one app at a time can receive the broadcast, and the Receiver must be registered with AudioManager to become active. This developer page demonstrates how to implement and register the Receiver. However, there are several misprints in that section. The System Service needs to be cast as AudioManager, and the registerMediaButtonEventReceiver() and unregisterMediaButtonEventReceiver() methods' calls should each have a ComponentName object as the parameter. For example:

AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);  
ComponentName receiverName = new ComponentName(mContext, RemoteControlReceiver.class);
...
// Start listening for button presses
am.registerMediaButtonEventReceiver(receiverName);
...

// Stop listening for button presses
am.unregisterMediaButtonEventReceiver(receiverName);

Upvotes: 2

Related Questions