javaandroidandroid-activityandroid-dark-theme

How do I keep my android activity keep on going even if somebody switches from dark mode to day mode or vice versa (using Java)


The problem is that when I switch from dark mode to light mode (android dark mode and android light mode), the activity which was going on that works fine but a duplicate activity starts all over again.

Now this does not matter when you are just working with visuals because the new activity covers the screen and old activity is not displayed but I am also working with sounds so the sounds playing in both the activities are heard.

In short, when switching from dark mode to light (or vice versa), the ongoing activity continues while a duplicate activity of the very same one starts from the beginning. I don't want this new duplicate activity. How do I avoid it?

I don't think my code is required here. I require the answer in Java.


Solution

  • The description of your problem doesn't make much sense. Normally, if you change the light/dark mode setting, Android will kill the existing instance of your Activity and create a new instance, so that the new instance can recreate all the UI elements with the proper style. You say that Android isn't killing the existing instance, but it is starting a new instance and this doesn't make sense. You should add logging in onCreate() and onDestroy() to see if this is really going on, or if you are seeing something else.

    Note that you can prevent Android from restarting your Activity by adding

    android:configChanges="uiMode"
    

    to the <activity> declaration in the manifest.

    Instead of killing and recreating your Activity, the Android framework will instead call onConfigurationChanged() on the existing instance of the Activity. You will then need to handle the change yourself.