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?
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();
}