Android中双击返回键退出程序

请注明出处:http://blog.csdn.net/qq_23179075/article/details/60587202

Android中双击返回键退出程序

1.在MyAppliction中(继承Application)

    //运用list来保存们每一个activity是关键
    private List mList = new LinkedList();
    //为了实现每次使用该类时不创建新的对象而创建的静态对象
    private static MyApplication instance;

    //构造方法
    public MyApplication() {
    }
    //实例化一次
    public synchronized static MyApplication getInstance() {
        if (null == instance) {
            instance = new MyApplication();
        }
        return instance;
    }

    //添加要退出的Activity
    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    //关闭每一个list内的activity
    public void exit() {
        try {
            for (Activity activity : mList) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    //杀进程
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }


2.在你需要的关闭的Activity的onCreact()中加入

MyApplication.getInstance().addActivity(this);

3.你需要双击返回退出的界面加上

    /**
     * 两次返回退出
     */
    private long mExitTime;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 3000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                MyApplication.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

你可能感兴趣的:(Android中双击返回键退出程序)