最好的解决方案是不使用静态数据,而是使用Shared Preferences
或存储数据,Database
如果发生任何uncaught Exception
情况,显示一条消息Application has crashed and a report is sent to the admin
,然后重新启动导致崩溃的 Activity。这样用户可以继续使用该应用程序。
做同样的事情,但不要重新启动导致异常重新启动应用程序的 Activity。
创建一个用于处理的类unCaughtException
public class MyExceptionHandler implements
java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final Class<?> myActivityClass;
public MyExceptionHandler(Context context, Class<?> c) {
myContext = context;
myActivityClass = c;
}
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
System.err.println(stackTrace);// You can use LogCat too
Intent intent = new Intent(myContext, myActivityClass);
String s = stackTrace.toString();
//you can use this String to know what caused the exception and in which Activity
intent.putExtra("uncaughtException",
"Exception is: " + stackTrace.toString());
intent.putExtra("stacktrace", s);
myContext.startActivity(intent);
//for restarting the Activity
Process.killProcess(Process.myPid());
System.exit(0);
}
}
并在每个活动中创建此类的对象并将其设置为DefaultUncaughtExceptionHandler
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
YourCurrentActivity.class));