Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android error: recreate() must be called from main thread

Tags:

java

android

I am getting an Android error, even though the error message is quite obvious, i can't figure out how to make it work properly.

The error message is:

 java.lang.IllegalStateException: Must be called from main thread
        at android.app.Activity.recreate(Activity.java:4193)

In my app, a notification is sent to log out a user (when his token expires).

On older Android versions i am having no problems to do so, however from SDK 11 and up, i have to use the recreate() method. I get the error that it has to be called from the Main thread.

I moved the recreate() statement to the MainActivity class, this doesn't work when i call the method from the IntentService. I still get the same error. The messaging part is working just fine, just the handling of the logout message is resulting in this error.

Here are some snippets:

inside GcmIntentService.java

if (logout!=null) {
    VarControl.ma.logout();
}

inside MainActivity.java

public void logout() {
    deleteToken();
    closeWebView();
    restartApp();
}

public void restartApp() {
    if (Build.VERSION.SDK_INT >= 11) {
        this.recreate(); // THE ERROR OCCURS HERE
    }
    else{
        //left out this part because its not relevant
    }
}

How can i call recreate from the Main thread (but the code has to be handled on receiving the intent) ??

like image 358
Bart Hofma Avatar asked Dec 03 '14 10:12

Bart Hofma


1 Answers

If you want to run sthg on the main thread you can still do :

public void restartApp() {
    if (Build.VERSION.SDK_INT >= 11) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                recreate();
            }
        });
    }
    else{
    //left out this part because its not relevant
    }
}
like image 68
Xavier Falempin Avatar answered Oct 27 '22 00:10

Xavier Falempin