I have written a code to show Toast
when the headset media button is pressed.I used intent filter to do it. But the problem is when i press the media button it fires twice.
My Code is:
MainActivity.java
private MusicIntentReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver=new MusicIntentReceiver();
((AudioManager)getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(new ComponentName(
this,
MusicIntentReceiver.class));
}
@Override
public void onResume(){
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
IntentFilter filter1=new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
filter1.setPriority(100);
registerReceiver(myReceiver, filter);
registerReceiver(myReceiver,filter1);
super.onResume();
}
@Override
public void onPause() {
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
IntentFilter filter1=new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
filter1.setPriority(100);
registerReceiver(myReceiver, filter);
registerReceiver(myReceiver,filter1);
super.onPause();
}
BroadcastReceiver.java
public class MusicIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String intentAction=intent.getAction();
Toast.makeText(context, "Action: "+intentAction, Toast.LENGTH_SHORT).show();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
abortBroadcast();
}
}
Once for button down, once for button up.
KeyEvent keyEvent = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (keyEvent != null) {
if (event.getAction() == KeyEvent.ACTION_UP)
{
switch(keyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY:
.... &c.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With