【发布时间】:2018-12-11 12:24:46
【问题描述】:
我一直在寻找如何关闭安卓应用程序的解决方案。
收集所有涉及该主题的帖子,我最终构建了一个健康有效的解决方案,我想在这篇文章中分享
如果我在某个地方失败了,请纠正我。
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);
}
});
}
【问题讨论】:
-
您想为自己的应用程序或其他应用程序执行此操作?
-
此解决方案适用于我自己的应用程序
-
那么你想做什么?您要关闭其他应用程序吗?或者您想在不关闭服务的情况下关闭所有活动。
-
这是一个解决方案,我花了 5 个月的时间来理解和开发它,所以我分享它以确保没有人会犯这个错误。我想知道我的代码是否有误。
-
对于我自己的应用程序,我认为这也是一个解决方案。 Intent i=new Intent(this,FinishActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);开始活动(一);在完成活动 onCreate(){ finish(); }
标签: android exit back-button-control