onResume not called after recreate in Activity

2k Views Asked by At

I'm calling recreate in onActivityResult of MainActivity when certain changes are made in the app settings. After recreation, onResume is not called.

I'm also getting the error:

E/ActivityThread: Performing pause of activity that is not resumed

From this question, I understood that this function can't be called from onResume. But I'm calling them from onActivityResult. Also using handler to call recreate resolves the problem, but causes a blink that looks bad to the user. What could be the possibly wrong here? How can I use recreate without a Handler?

Any ideas will be appreciated. Thanks!

2

There are 2 best solutions below

1
On

I finally solved the problem by sending a broadcast from the SettingsActivity to the BroadcastReciever in the MainActivity and calling recreate() inside onRecieve().

10
On

OnActivityResult() is called before onResume(). What you can do is set a flag in the OnActivityResult() that you can check in the onResume() and if the flag is true you can recreate the activity.

What you could actually do is to finish the activity and start the same one, isntead of recreating it. You will get the same effect. it could be something like this:

public class MainActivity extends AppCompatActivity   {

private boolean shouldRecreate = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("AG", "onCreate() called");
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivityForResult(intent, 0);
}

@Override
protected void onResume() {
    super.onResume();
    if (shouldRecreate){
        finish();
        startActivity(new Intent(this, MainActivity.class));
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 0){
        shouldRecreate = true;
    }
}
}