BroadcastReceiver for ACTION_MEDIA_BUTTON not working

I tested this on a Samsung Galaxy S5 with Android 4.4.2. So what is important and what is not mentioned in other posts:

  • Register the receiver in the AndroidManifest.xml inside the application tag but outside from every activity tag.
  • Your receiver Broadcastreceiver need to be public and static
  • One activity need to register an MediaButtonEventReceiver to listen for the button presses

Okay and here some example code:

mAudioManager =  (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mReceiverComponent = new ComponentName(this,YourBroadcastReceiver.class);
...
mAudioManager.registerMediaButtonEventReceiver(mReceiverComponent);
...
// somewhere else
mAudioManager.unregisterMediaButtonEventReceiver(mReceiverComponent);

Here the receiver:

public static class YourBroadcastReceiver extends BroadcastReceiver{

    // Constructor is mandatory
    public MediaBroadcastReceiver ()
    {
        super ();
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        Log.i (TAG_MEDIA, intentAction.toString() + " happended");
        if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
            Log.i (TAG_MEDIA, "no media button information");
            return;
        }
        KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            Log.i (TAG_MEDIA, "no keypress");
            return;
        }
        // other stuff you want to do
    }
}

And here the manifest snippet. If needed add priority for the intent-filter, but was not needed for me:

<application>
    <receiver android:name="OuterClass$YourBroadcastReceiver">
        <intent-filter>
           <action android:name="android.intent.action.MEDIA_BUTTON" />
         </intent-filter>
    </receiver>
    <activity> ... </activity>
</application>

For the references:

  • http://developer.android.com/training/managing-audio/volume-playback.html
  • MediaButtonIntentReceiver not working in Android 4.0+
  • BroadcastReceiver: can't instantiate class; no empty constructor

mediaButtonReceiver = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());

mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

mAudioManager.registerMediaButtonEventReceiver(mediaButtonReceiver);

This code will bind your headphone button to your app and your app only until you call:

mAudioManager.unregisterMediaButtonEventReceiver(mediaButtonReceiver);

You can avoid to use the Broacastreceiver for Android >5.0 (API level 21 LOLLIPOP) using the MediaSession described here: https://stackoverflow.com/a/39413753/1386969