安卓 : avoid crashing of app due to unhandled errors

标签 android exception-handling

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

我已经使用了 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
  }
}

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

关于安卓 : avoid crashing of app due to unhandled errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6153454/

相关文章:

android - 月球着陆器示例中的缺陷(IllegalThreadStateException)

android - 包含图标的 ToggleButton 矩形

c# - C#HttpWebRequest的错误处理

.net - 在 ASP.NET MVC 应用程序中在哪里定义异常处理和错误日志记录的最佳实践?

android - 如何检测设备上是否存在 Android Market?

Android 在解析 XML 时出错 - 在第 1 行,第 0 列 - 未找到元素

Java - 应该在哪里以及如何使用异常?

powershell - 如何处理 Copy-Item 异常?

java - Spring @ControllerAdvice 不起作用

android - 如何使用 Robolectric 3.0 从服务器测试 ListView 项目