Jose
Jose

Reputation: 73

How to handle earphones button clicks?

I have this code to handle button clicks from earphones. The problem is that my priority is low and when i click the button the radio turns on. I want to be able to give priority to my app. I tried to increase the setPriority number but it does not work.

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_MULTIPLE) {
            // do something
            Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
        }
        abortBroadcast();
    }

//Code in other class

   IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
        MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
        filter.setPriority(1000); **//increasing this does not work**
        registerReceiver(r, filter);

Upvotes: 0

Views: 1907

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 200120

You cannot register a receiver for Intent.ACTION_MEDIA_BUTTON with registerReceiver as it is handled separately by the Media framework to dispatch to the correct media app as described in the Responding to Media Buttons guide.

However, in the case where you want to handle it in the foreground, you don't need to use Intent.ACTION_MEDIA_BUTTON at all as all KeyEvents are first sent to the active Activity via onKeyDown() (and onKeyUp()). Therefore you can handle the KeyEvent directly:

@Override
public boolean onKeyDown (int keyCode, 
            KeyEvent event) {
  // This is the center button for headphones
  if (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK) {
    Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
    return true;
  }
  return super.onKeyDown(keyCode, event);
}

Upvotes: 3

Related Questions