转载请注明出处:http://blog.csdn.net/javacattle/article/details/41964045
只要在 *.Java 文件中添加即可
private int back = 0;
//===============back两次退出=====================
@Override
public boolean onCreateOptionsMenu(Menu menu) {//必要的改变
menu.add(0, 2, 2, "退出");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 2:
Myback();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {//两次back退出
if (keyCode == KeyEvent.KEYCODE_BACK) {
back++;
switch (back) {
case 1:
Toast.makeText(MainActivity.this, "再按一次退出",
Toast.LENGTH_SHORT).show();
break;
case 2:
back = 0;// 初始化back值
Myback();
break;
}
return true;// 设置成false让back失效 ,true表示 不失效
} else {
return super.onKeyDown(keyCode, event);
}
}
public void Myback() { // 关闭程序
MainActivity.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());// 关闭进程
}