我一直在寻找有关如何关闭 android 应用程序的解决方案。
收集所有涉及该主题的帖子,我最终构建了一个健康有效的解决方案,我想在这篇文章中分享
如果我在某个地方失败了,请纠正我。
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);
}
});
}