kibibyte
kibibyte

Reputation: 3037

Is it possible to create some sort of global exception handler in Android?

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 weird 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?

Upvotes: 2

Views: 3960

Answers (2)

zaman
zaman

Reputation: 786

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"

Upvotes: 2

Ovidiu Latcu
Ovidiu Latcu

Reputation: 72341

    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler()... );

Upvotes: 0

Related Questions