我想避免应用程序崩溃,然后我开发了uncaughtException方法来调用另一个活动;它工作正常。如果应用程序崩溃了任何活动,则调用uncaughtException,然后显示我的ErrorActivity。 问题是我在崩溃后尝试关闭应用程序。当我按下后退按钮时,ErrorActivity将关闭,但随后显示带有操作栏的白色屏幕,几秒钟后再次调用ErrorActivity。因此,除非在任务管理器中完成应用程序,否则无法关闭应用程序。
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException (Thread thread, Throwable e)
{
handleUncaughtException (thread, e);
}
});
}
public void handleUncaughtException (Thread thread, Throwable exception)
{
StringWriter _stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(_stackTrace));
Intent _intent = new Intent();
_intent.setAction ("com.mypackage.ERROR_ACTIVITY");
_intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
_intent.putExtra("error", _stackTrace.toString());
startActivity(_intent);
System.exit(0);
}
答案 0 :(得分:0)
试试这个:
public void handleUncaughtException (Thread thread, Throwable exception)
{
StringWriter _stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(_stackTrace));
Intent _intent = new Intent();
_intent.setAction ("com.mypackage.ERROR_ACTIVITY");
_intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
_intent.putExtra("error", _stackTrace.toString());
startActivity(_intent);
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
finish();
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
当应用崩溃时执行system.exit()
,这意味着它不是常规system.exit()
,但它是例外,并且意味着您最好使用system.exit(1)
而不是system.exit(0)
,这可能会解决您的问题。这是来自Java Documentation" 终止状态。按照惯例,非零状态代码表示异常终止。"。
<强>更新强>
尝试将意图标记从NEW_TASK
更改为CLEAR_TOP
:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
答案 2 :(得分:0)
我找到了解决方案。它只是添加Intent.FLAG_ACTIVITY_CLEAR_TASK
如下:
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException (Thread thread, Throwable e)
{
handleUncaughtException (thread, e);
}
});
}
public void handleUncaughtException (Thread thread, Throwable exception)
{
StringWriter _stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(_stackTrace));
Intent _intent = new Intent();
_intent.setAction("br.com.magazineluiza.mobilevendas.ERROR_ACTIVITY");
_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // Here is the solution
_intent.putExtra("error", _stackTrace.toString());
startActivity(_intent);
System.exit(0); // or System.exit(1) It doesn't matter
}