Arc*_*pgc 8 android toast uncaught-exception uncaughtexceptionhandler
我正在使用此代码来处理可能导致我的应用程序崩溃的任何未捕获的异常.
public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
public ExceptionHandler(Context context) {
myContext = context;
}
public void uncaughtException(Thread thread, Throwable exception) {
Toast.makeText(myContext,
"The application has crashed, and a report is sent to the admin",
Toast.LENGTH_SHORT).show();
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
System.err.println(stackTrace);// You can use LogCat too
Intent intent = new Intent(myContext, CrashActivity.class);
myContext.startActivity(intent);
Process.killProcess(Process.myPid());
System.exit(10);
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用已知但未捕获的异常(仅测试)运行它时,会调用活动"CrashActivity",但必须在它之前出现的Toast才会显示.
其实我只想显示Toast,然后调用myContext.finish(); 而不是去CrashActivity.但那种敬酒不可见.
我哪里错了?
在google搜索完全相同的问题时发现了这个问题.据我所知Toast.show(),只要有一个Application上下文就没有必要从UI线程中调用.
AFAIK:此处出现的问题如下:您正在尝试显示Toast,之后您的应用程序会立即被VM关闭,这意味着您的Toast也会关闭.
该问题的解决方案如下:
我所做的是以下内容:
在Application::onCreate():
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex)
{
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(getApplicationContext(), "Application crashed", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
try
{
Thread.sleep(4000); // Let the Toast display before app will get shutdown
}
catch (InterruptedException e)
{
// Ignored.
}
}
});
Run Code Online (Sandbox Code Playgroud)
它类似于ACRA中的Toast通知如何工作(实际上这是我得到提示的地方).
| 归档时间: |
|
| 查看次数: |
5751 次 |
| 最近记录: |