I am writing an Android application for version 4.0.3 (ICS) of the Android OS. The issue is that I am not getting the output from my Log.d() in the onReceive() method of the
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:
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:
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