以编程方式关闭 Android 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22602365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Closing Android application programmatically
提问by user3048027
I am working on an Android
project the requirement is as follows: if any exceptions
occur we need to exit the application by showing error
message.
我正在处理一个Android
项目,要求如下:如果exceptions
发生任何情况,我们需要通过显示error
消息退出应用程序。
I am aware that Android
doesn't allow to exit application programmatically so other work around should be to freeze the application that is user should not be able to do anything in the application. But how do I implement this.
我知道Android
不允许以编程方式退出应用程序,因此其他解决方法应该是冻结用户不应在应用程序中执行任何操作的应用程序。但是我如何实现这一点。
回答by Tushar Narang
hey call this function when error occurs its simple
嘿当错误发生时调用这个函数很简单
public void close()
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
回答by Android
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
(But using system.exit()
is a bad approach in android. Better to use finish()
)
(但system.exit()
在android中使用是一种不好的方法。更好地使用finish()
)
OR
或者
Intent i= new Intent(getapplicationcontext,TARGETACTIVITY.class);
finish();
startActivity(intent);
回答by Sethu
try this one:
试试这个:
try{
-------
-----
----
}
Catch (Exception e)
{
exception.printStackTrace();//using alert box to show your exception.
finish(); //use this one of your Application it will close the application.
}
or else try to use service of create a new intent of your alertbox activity:
或者尝试使用创建警报框活动的新意图的服务:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
回答by Raj Kumar
Write this code in your on backpressed override method
将此代码写入您的 on backpressed 覆盖方法中
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
回答by Anas Reza
Just call
打电话就行
System.exit();
in your catch block
在你的 catch 块中