Android:避免由于未处理的错误导致应用崩溃

时间:2011-05-27 14:10:05

标签: android exception-handling

在我的Android应用中,我尝试将Try Catch块放在所有可能的位置。但是我希望避免由于任何未处理的错误导致应用程序崩溃。我怎样才能做到这一点?

我使用过Thread.setDefaultUncaughtExceptionHandler(handler);但这只会帮助我获取崩溃数据吗?

5 个答案:

答案 0 :(得分:6)

您可以使用以下方式:

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
  }
}

将处理您的应用意外崩溃,这取自that answer

答案 1 :(得分:2)

你为什么要这样做?

如果有些地方可以捕获异常并执行一些有意义的操作,即显示有用的警告,然后继续处于一致且可用状态的应用程序,那么很好。

如果你不能采取任何有意义的行动,那就让失败发生。有很多方法可以通知您产生的故障,因此您可以修复它们:例如,查看ACRA。或者,Android Developer控制台现在将报告您的市场分布式应用程序的失败。

答案 2 :(得分:2)

我建议您阅读有关ACRA here

的信息

答案 3 :(得分:0)

所有错误和异常都从Throwable扩展。通过捕获Throwable,可以处理所有意外情况。但是捕捉错误会产生影响。您可以在应用程序崩溃之前在catch块中执行smth

答案 4 :(得分:0)

相关问题