My application includes a series of Activities, through which the user must proceed in a linear fashion. Let's say that this series of activities looks like this: A (represents the main menu), B, C, D, E. The user proceeds like this: A -> B -> C -> D -> E. In each of these activities, the user must either input data or allow the device to get the data automatically (e.g. via the network or Bluetooth).
Occasionally, my app crashes in one of the middle activities. What ends up happening, typically, is that the app moves back an activity or two. For example, if my app crashes in Activity D, the app might move back to Activity C or B. But the problem is, after such a crash, the input data is in such a weir开发者_StackOverflow中文版d state that the app again crashes and shows the force close dialog, all the way back to Activity A, the main menu.
How can I catch these exceptions that cause these crashes globally throughout the application, so I can clean up the data and gracefully allow the user to return to the main menu?
Extend Application class
import android.app.Application;
import android.util.Log;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("MyApplication", ex.getMessage());
}
});
}
}
Add the following line in AndroidManifest.xml file as Application attribute
android:name=".MyApplication"
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler()... );
精彩评论