编程语言
首页 > 编程语言> > java – 在Android中双击耳机按钮

java – 在Android中双击耳机按钮

作者:互联网

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

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

}

但它只是检测单击.两次单击而不是双击.哪里有问题?

解决方法:

正确的解决方案:

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

标签:double-click,android,java,broadcastreceiver
来源: https://codeday.me/bug/20190825/1717792.html