在我的 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/