Vishal Afre
Vishal Afre

Reputation: 1043

Start activity without context

I'm using a custom Exception Handler in my android app so that whenever the app crashes, its overridden method uncaughtException(Thread t, Throwable e) is called. In that method, I want to start an activity which prompts the user to mail the error log to the developer.

But the problem is, I'm not getting any context to start the activity. I also tried passing the context of previous activity to that method but as the app is stopped after crashing, the context is also gone and hence the activity could not be started with it.

Here is my Application Class onCreate method

@Override
    public void onCreate() {
        super.onCreate();

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                Intent i = new Intent(QuickTatkalApp.this, HomeActivity.class);
                startActivity(i);
            }
        });
    }

What I'm getting after this is whenever the app is crashing, only a blank white screen is shown in the app.

Upvotes: 0

Views: 502

Answers (1)

Abner Escócio
Abner Escócio

Reputation: 2785

Try create a class with extends from Application as follow

public final class MyAppApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                //start your activity here with Application#packageContext
                //just calling "this"
            }
        });
    }
}

Upvotes: 1

Related Questions