Android back键监听退出应用的两种方式

Android back键监听退出应用的两种方式

一、 弹出对话框退出:

在主Activity中 进行。。。

@Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("确定要退出吗?")
                    .setCancelable(false)
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int id) {
                                    Intent intent = new Intent(Intent.ACTION_MAIN);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置启动的界面在新的栈中
                                    intent.addCategory(Intent.CATEGORY_HOME);//启动Home界面
                                    startActivity(intent);
                                }
                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,  int id) {
                                    dialog.cancel();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }


二、两秒内按两次back键退出程序:

    /**
     * 标记是否退出系统
     */
    private static final int WHAT_BACK = 1;

    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
                if(msg.what == WHAT_BACK) {
                    isBack = false ;
             }
         }
    };

    /**
     * 标记back键是否起作用
     */
    private boolean isBack = false ;
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        /**
         * back键起作用依赖系统,因此我们只能让他在两秒之后再按back键恢复到第一次按back键的状态
         * 能执行 super.onKeyUp(keyCode, event);的时候back键起作用
         */
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if(!isBack) {
                Toast.makeText(MainActivity.this, "再按一次back键退出零食小喵", Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessageDelayed(WHAT_BACK, 2000);
                isBack = true ;
                return true ;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if(handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

你可能感兴趣的:(Android)