This problem occurs on LG G4 (Android version 5.1) only.
My Application uses headset's play/pause button to trigger an action. I implemented the BroadcastReceiver as:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() { super(); }
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
Log.v("MediaButton: ", "Action_Down");
// Some action
}
}
}
And I am registering the receiver with:
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
filter.setPriority(10000);
registerReceiver(new MediaButtonIntentReceiver(), filter);
This code works perfectly on various smartphones, except LG G4. Lg phone almost always starts the Music Widget and my logcat says:
01-08 11:49:30.230 22031-22031/com.example.test I/ViewRootImpl: ViewRoot's KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_HEADSETHOOK, scanCode=226, metaState=0, flags=0x8, repeatCount=0, eventTime=285960, downTime=285960, source=0x101 } to com.android.internal.policy.impl.PhoneWindow$DecorView{10cba8ca V.E..... R....... 0,0-1440,2560}
After some search on SO, I implemented a MediaSession to make my application the sole receiver of the ACTION_MEDIA_BUTTON intent with the below code:
MediaSession mediaSession = new MediaSession(this, "MediaSessionTAG");
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS);
//Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); // this doesn't work either
Intent mediaButtonIntent = new Intent(getApplicationContext(), MediaButtonIntentReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0);
mediaSession.setMediaButtonReceiver(pIntent);
mediaSession.setActive(true);
How can I make my application the only receiver of the Media Button intent and have the MediaButtonIntentReceiver (BroadcastReceiver) called at each button action?