问题
Detect Headset buttons double click and Long press(click) Android
I am trying the bellow code
public class MediaButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("----onReceive--", " ");
if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
Log.e("----jack out--", " ");
if (intent.getExtras().getInt("state") == 1)// if plugged
Toast.makeText(context, "earphones plugged", Toast.LENGTH_LONG)
.show();
else
Toast.makeText(context, "earphones un-plugged",
Toast.LENGTH_LONG).show();
}
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
Toast.makeText(context, "button pressed", Toast.LENGTH_LONG).show();
// key=intent.getExtras().getString("EXTRA_KEY_EVENT");
}
abortBroadcast();
}
It detects the headset button click correctly
However how can we detect long click and double click for headset
回答1:
For the double click you can detect it by overriding Activity onKeyDown
method and measuring time elapsed between each click:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HEADSETHOOK){
//check if it's the first or the second click and measure time between them
return true;
}
return super.onKeyDown(keyCode, event);
}
There's also an Activity onKeyLongPress
method but it doesn't seem to work on my device with headset button as when I long press headset button it launches Google Now and I can't detect it inside my activity
来源:https://stackoverflow.com/questions/36172380/detect-headset-buttons-double-click-and-long-pressclick-android