Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle audiojack button

Tags:

android

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!

like image 309
benoffi7 Avatar asked Aug 13 '26 17:08

benoffi7


1 Answers

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);
like image 131
Mike M. Avatar answered Aug 15 '26 08:08

Mike M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!