菜鸟的安卓实习之路---在按一次退出程序

直接贴代码吧,这应该是最简单的方式了,利用2秒的时间差来判断的:

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (DateUtil.getSystemTimeMillis() - exitTime > 2000) {
                showToast("在按一次返回,退出XXX!");
                exitTime = DateUtil.getSystemTimeMillis();
            } else {
                exitApp(MainActivity.this);
            }
        }
        return false;
    }


这里的onKeyDown()  是用来监听没有被活动内部的view处理的事件监听器。 看看他自己怎么说:

 Called when a key was pressed down and not handled by any of the views inside of the activity. So, for example, key presses while the cursor  is inside a TextView will not trigger the event (unless it is a navigation  to another object) because TextView handles its own key presses.

你可能感兴趣的:(安卓)