0

I use a broadcast receiver for detect headset button actions. I use this code in onReceive function for long click:

@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();

    switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_HEADSETHOOK:
            if (action == KeyEvent.FLAG_LONG_PRESS)
                Toast.makeText(context, "Long click!", Toast.LENGTH_SHORT).show();
        break;
    }
    abortBroadcast();

}

But it didn't work.Where is the problem? Is there any other way?

Mehrdad
  • 708
  • 1
  • 17
  • 38

1 Answers1

1

Here's the solution:

 @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();

    switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_HEADSETHOOK:
            if (action == KeyEvent.ACTION_UP)
                if (SystemClock.uptimeMillis() - event.getDownTime() > 2000) 
                     Toast.makeText(context, "Long click!", Toast.LENGTH_SHORT).show();
        break;
    }
    abortBroadcast();

}
Mehrdad
  • 708
  • 1
  • 17
  • 38
  • @UpendraShah make sure your broadcast listener gets called. In some cases other apps prevent the you app's listener to get the events. – Mehrdad Aug 03 '17 at 14:16