以编程方式关闭 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:13:59  来源:igfitidea点击:

Closing Android application programmatically

androidexit

提问by user3048027

I am working on an Androidproject the requirement is as follows: if any exceptionsoccur we need to exit the application by showing errormessage.

我正在处理一个Android项目,要求如下:如果exceptions发生任何情况,我们需要通过显示error消息退出应用程序。

I am aware that Androiddoesn'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 块中