Tus*_*kar 8 android exception-handling
在我的Android应用程序中,我试图将Try Catch块放在所有可能的位置.但是我希望避免由于任何未处理的错误导致应用程序崩溃.我怎样才能做到这一点?
我已经习惯Thread.setDefaultUncaughtExceptionHandler(handler);但这只会帮助我获得崩溃数据吗?
您可以使用以下方式:
public class MyApplication extends Application
{
public void onCreate ()
{
// Setup handler for uncaught exceptions.
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException (Thread thread, Throwable e)
{
handleUncaughtException (thread, e);
}
});
}
// here you can handle all unexpected crashes
public void handleUncaughtException (Thread thread, Throwable e)
{
e.printStackTrace(); // not all Android versions will print the stack trace automatically
Intent intent = new Intent ();
intent.setAction ("com.mydomain.SEND_LOG"); // see step 5.
intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
startActivity (intent);
System.exit(1); // kill off the crashed app
}
}
Run Code Online (Sandbox Code Playgroud)
这将处理您的应用程序意外崩溃,这取自该答案.
你为什么要这样做?
如果在某些地方您可以捕获异常并执行一些有意义的操作,即显示有用的警告,然后继续以一致且可用的状态运行应用程序,那么就可以了。
如果你不能采取任何有意义的行动,那就让失败发生吧。有很多方法可以通知您所产生的故障,以便您可以修复它们:例如,查看ACRA 。或者,Android 开发者控制台现在将报告市场分发的应用程序的失败。
| 归档时间: |
|
| 查看次数: |
14746 次 |
| 最近记录: |