耳机按钮双击android

时间:2013-12-23 21:32:24

标签: java android broadcastreceiver double-click

我使用此代码检测广播接收器中的单击和双击耳机按钮:

int d = 0;
@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_DOWN) {
                d++;
                Handler handler = new Handler();
                Runnable r = new Runnable() {                   
                    @Override
                    public void run() {
                        Toast.makeText(context, "single click!", Toast.LENGTH_SHORT).show();
                        d = 0;
                    }
                };
                if (d == 1) {
                    handler.postDelayed(r, 500);
                } else if (d == 2) {
                    d = 0;
                    Toast.makeText(context, "double click!", Toast.LENGTH_SHORT).show();
                }
            }break;
    }
    abortBroadcast();

}

但它只是检测到单击。两次单击而不是双击。问题出在哪里?

1 个答案:

答案 0 :(得分:6)

正确的解决方案:

static int d = 0;
@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_DOWN) {
            d++;
            Handler handler = new Handler();
            Runnable r = new Runnable() {

            @Override
            public void run() {
                    // single click *******************************
                    if (d == 1) {
                                Toast.makeText(context, "single click!", Toast.LENGTH_SHORT).show();
                    }
                    // double click *********************************
                    if (d == 2) {
                        Toast.makeText(context, "Double click!!", Toast.LENGTH_SHORT).show();
                    }
                    d = 0;
            }
            };
            if (d == 1) {
                    handler.postDelayed(r, 500);
            }
        }break;
   }
   abortBroadcast();
}