Android中的“再按一次返回键退出程序”功能实现

来源:互联网 发布:最燃的一句话 知乎 编辑:程序博客网 时间:2024/05/22 10:41

  在项目中用到的双击退出应用,后面那个代码是退出整个应用,不会因为多次点击出现内存溢出。

/**

     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {   
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                exitBy2Click(); // 调用双击退出函数
            }  
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;
    private String stringExtra;
    private String addressCitys;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务

        } else {   

          // System.exit(0);
            // android.os.Process.killProcess(android.os.Process.myPid());

            int currentVersion = android.os.Build.VERSION.SDK_INT;
            if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);
            } else {// android2.1
                // android:largeHeap="true"
                // android:hardwareAccelerated="true"
                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                am.restartPackage(getPackageName());
                Log.d("MainActivity", getPackageName());
            }
        }
    }
1 0
原创粉丝点击