JDS JDS - 1 year ago 198
Java Question

Android - registering a headset button click with BroadcastReceiver

Alright, so I have a headset w/ single button and want to do a simple Toast when the button is pressed.

Right now I have the following code:

public class MediaButtonIntentReceiver extends BroadcastReceiver {

public MediaButtonIntentReceiver() {

public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();

And my main activity is the following:

public class mainActivity extends Activity {

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {

IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
registerReceiver(r, filter);


Nothing happens though when I push the button though.

I'm pretty sure something is wrong with my permissions/xml in the manifest. Here's the receiver XML so far:

<receiver android:name=".MediaButtonIntentReceiver">
<action android:name="android.intent.action.MEDIA_BUTTON" />



I notice in LogCat that when I press the button I get an error from "BluetoothIntentReceiver" saying "onReceive() Action : android.intent.action.MEDIA_BUTTON"

Thanks for any help guys, been really stuck on this the last few days.

Answer Source

Just wanted to answer my own question in case others come across similar issues.

The code does work, just I wasn't seeing the Toast because I had another headset button controller app installed (and running in the background), so I guess it took priority over mine. However when I put

    IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
    MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
    filter.setPriority(1000); //this line sets receiver priority
    registerReceiver(r, filter);

It was able to work even with the other app installed. Also, you don't need both the above AND the XML, one or the other is fine as ways of registering the intent receiver.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download