简体   繁体   中英

How to go back to previous activity after clearing task?

Sorry if title is not clear, here's an in-depth explanation:

I'm in the Settings activity of my app and I have an option to change the app's theme. Obviously I want the entire theme of the app to change immediately when I change this option. So I'm using OnSharedPreferenceChangeListener in this way:

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals("theme_preference")) {
        Intent refresh = new Intent(getApplicationContext(), SettingsActivity.class);
        refresh.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); //clears previous activities
        startActivity(refresh);
    }
}

As you can see I added flags that would clear the previous activities so that they'll be recreated too to have their themes updated.

The Settings activity recreates itself just fine, but then when I press the Up or Back button to go back to the previous activity the app crashes. Why is it crashing?

This is how you start a stack of activities:

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
stackBuilder.addNextIntentWithParentStack(intent);
Intent nextIntent = ...;
stackBuilder.addNextIntent(nextIntent);
stackBuilder.startActivities();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM