我的应用有问题,我想在点击后退按钮时关闭我的应用。 但是当从这个屏幕点击返回时,应用程序返回到prev屏幕。我尝试添加所有退出脚本,但不能正常工作,请帮助。 我的剧本是:
public void onBackPressed() {
Exit = new AlertDialog.Builder(tab1.this).create();
Exit.setTitle("Exit Program");
Exit.setMessage("Exit?");
Exit.setButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
android.os.Process.killProcess(android.os.Process.myPid());
Intent intent = new Intent();
System.exit(0);
finish();
System.runFinalizersOnExit(true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
Exit.setButton2("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
Exit.dismiss();
}
});
Exit.show();
}
// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Exit = new AlertDialog.Builder(tab1.this).create();
Exit.setTitle("Exit Program");
Exit.setMessage("Exit?");
Exit.setButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Progress
android.os.Process.killProcess(android.os.Process.myPid());
Intent intent = new Intent();
System.exit(0);
finish();
System.runFinalizersOnExit(true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
Exit.setButton2("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
Exit.dismiss();
}
});
Exit.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
答案 0 :(得分:0)
尝试以下顺序:
MYApplication.getInstance().clearApplicationData();
android.os.Process.killProcess(android.os.Process.myPid());
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addCategory(Intent.CATEGORY_HOME);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent1);
finish();
答案 1 :(得分:0)
在我看来,这是一种以编程方式退出Android应用程序的公平而简单的方法:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
希望它有所帮助。
答案 2 :(得分:-2)
避免killProcess
请尝试以下代码:
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(startMain);
System.exit(-1);