Android press the return key twice to exit the program

Many applications have the setting to exit the program by pressing the return key twice. In fact, it is very simple. This is achieved by broadcasting.
First define a BaseActivity, so that all activities inherit from this class, define a broadcast receiving class in this class, and finish() after receiving the broadcast, so that all activities will have this method to receive the broadcast, and they will all finish is over.
Register the broadcast in the onResume() method, cancel the broadcast when this class is destroyed, remember to destroy, otherwise it will keep occupying system memory.

public class BaseActivity extends Activity {
    
    
    BroadcastReceiver finishApplicationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            finish();
        }
    };

    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.gouchao");
        this.registerReceiver(finishApplicationBroadcastReceiver, filter);
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        this.unregisterReceiver(finishApplicationBroadcastReceiver);
        super.onDestroy();
    }
}

Send a broadcast in the Activity where you need to press the return key twice to exit the program.

    // 连按两次退出应用
    // 记录时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                exitApp();
            }
        }
        return true;
    }
    //发送广播
    public void exitApp() {
        Intent intent = new Intent();
        intent.setAction("com.example.gouchao");
        this.sendBroadcast(intent);
    }

Remember to return true in the onKeyDown() method, otherwise press the return key once to return to the previous Activity directly

Guess you like

Origin blog.csdn.net/lizebin_bin/article/details/49824447