在Android開發(fā)過程中總會(huì)遇到需要完全退出應(yīng)用程序的需求,試過很多個(gè),發(fā)現(xiàn)這種方法最簡(jiǎn)潔:
首先在AndroidManifest中把程序的的主界面比如MainActivity的launchMode指定為singleTask。
android:launchMode="singleTask"
然后在需要退出程序的地方用如下代碼;
@Override
public void onBackPressed() {
if ((System.currentTimeMillis() - exit_time) > 2000) {
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exit_time = System.currentTimeMillis();
return;
}
Intent exitIntent = new Intent(this, MainActivity.class);
exitIntent.putExtra("ASKFOR_EXIT", true);
startActivity(exitIntent);
finish();
}
最后在MainActivity中加入如下代碼:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null) {
if (intent.hasExtra("ASKFOR_EXIT")) {
finish();
}
}
}