简体   繁体   中英

Double tap physical button on android

I am currently developing an android app. I have an activity which calls a web view activity. When the user presses the back button once it will go to the history of the webview, when the user double taps the back button I want the webview activity to finish.

How can I go about checking for a double tap of the back button

Just keep track of the last tap on the back button. If the current tap is in a specific time limit (maybe 1 second) after the last tap, then it was a double tap. Otherwise its just a normal tap.

I think you need a Handler.

private int mCount;

private void handleBackKeyDown() {
    if (mCount > 0) {
        mCount = 0;
        mMyHandler.removeMessages(MyHandler.MSG_GO_TO_HISTORY);
        finish(); // close this activity
    } else {
        mCount++;

        Message msg_reset = Message.obtain();
        msg_reset.what = MyHandler.MSG_GO_TO_HISTORY;
        mMyHandler.sendMessageDelayed(msg_reset, TIME_TO_START_OVER_AGAIN);
    }
}

private class MyHandler extends Handler {
    public static final int MSG_GO_TO_HISTORY = 0;
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case MSG_GO_TO_HISTORY:
            // go to the history of the webview
            mCount = 0;
            break;
        default:
            break;
        }
    }
}

I think in this case, what you want is a long press on the back button. (although I believe this may have conflicts with 6.2+ cyanogen roms if the user has that feature turned on...) A double tap on the back button might be a little disruptive on a mobile device.

Following the typical way to override buttons, I'm assuming you know how to (if you need more help just say so), There must be a onLongPress(...) method that you can override to do what you want it to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM