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:

Leave a Comment