public class MainActivity extends AppCompatActivity {
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler(Looper.getMainLooper());
}
boolean enableDoubleBackExit = true;
boolean backPressedOnce = false;
@Override
public void onBackPressed() {
if (!enableDoubleBackExit) {
super.onBackPressed();
return;
}
if (!backPressedOnce) {
backPressedOnce = true;
Toast.makeText(this, "再按一次返回键关闭程序", Toast.LENGTH_SHORT).show();
handler.postDelayed(() -> backPressedOnce = false, 2000);
} else {
exit();
}
}
protected void exit() {
Log.e("exit");
finish();
Log.e("finished");
}
@Override
protected void onDestroy() {
super.onDestroy();
Looper.myQueue().addIdleHandler(() -> {
Log.e("try kill process");
Process.killProcess(Process.myPid());
System.exit(0);
return false;
});
}
}
如果在finish()后直接杀进程,不会走主页的onStop()和onDestroy(),可能会影响部分模块的功能。