KeyEvent.ACTION_UP fired TWICE for ACTION_MEDIA_BUTTON KeyEvent.ACTION_UP fired TWICE for ACTION_MEDIA_BUTTON android android

KeyEvent.ACTION_UP fired TWICE for ACTION_MEDIA_BUTTON


I noticed that you are using this receiver in a library (the "mylib" part in your manifest).

If this is indeed the case and you have that receiver registered by two applications sharing the same registration code, you will see those events twice.

If three applications register that receiver, you will receive those events tripled...

Make sure that each application uses a different (unique) <receiver android:name.


I ran across this issue and spent a while banging my head against the wall before I realized that each press of the button generates two events: a KeyEvent.ACTION_DOWN, and a KeyEvent.ACTION_UP. So two tests are needed to use a media button:

if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {}

and

if (event.getAction() == KeyEvent.ACTION_DOWN) {}

So if anyone else finds themselves here as a result of the same mistake, perhaps this reply will help.


For ensuring that it's the first time always you can use a flag to tell that it's the first action.

boolean firstAction= false;if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {    firstAction= !firstAction;    if(!firstAction)    {        return true;    }    KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);    long curEventTime = event.getEventTime();    if (event != null && (event.getAction() == KeyEvent.ACTION_UP) /*&& (curEventTime != prevEventTime)*/) {        int keycode = event.getKeyCode();        switch (keycode)        {          case KeyEvent.KEYCODE_MEDIA_NEXT:            Log.i(TAG, "KEYCODE_MEDIA_NEXT");             break;          case KeyEvent.KEYCODE_HEADSETHOOK:            Log.i(TAG, "KEYCODE_HEADSETHOOK" + " " +  curEventTime + " <> " + prevEventTime + " (" + event.getAction() + ")");            prevEventTime = curEventTime;            break;          case KeyEvent.KEYCODE_MEDIA_PREVIOUS:            Log.i(TAG, "KEYCODE_MEDIA_PREVIOUS");             break;          default:        }    }     }