Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
先退出到桌面,然后杀死所有进程。这样就不用烦恼,很多activity反复跳出了。
下面给出一个常用的按两次退出程序的写法
private long exitTime; //两次返回键退出之间的间隔
//按两次退出程序
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN) {
if ((System.currentTimeMillis() - exitTime) > 2000) // System.currentTimeMillis()无论何时调用,肯定大于2000
{
Toast.makeText(getApplicationContext(), "亲爱滴,再按一次退出程序",
Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}
return true;
}
return super.onKeyDown(keyCode, event);
}