我一直在寻找一个解决方案来关闭安卓应用程序。
通过收集所有处理此问题的帖子,我最终建立了一个健康有效的解决方案,我想在这篇文章中分享。
如果我有任何错误,请纠正我。
public static void closeApp(Activity activity) {
//Go to home to change main android view and focus
//You can remove this part
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
//finish in background many activities as possible
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.finishAndRemoveTask();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
activity.finishAffinity();
} else {
activity.finish();
}
//Kill all existing app process
activity.moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
//close the app
System.exit(0);
}
使用示例
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
closeApp(MainActivity.this);
}
});
}