Categories
discuss

Android 12: How to prevent activity restart on changing phone wallpaper?

On Android 12, If we open an activity Go to the home screen of the phone to change the wallpaper Switch back to our activity, the activity restarts. It seems it is related to the Material You …

On Android 12,

  1. If we open an activity

  2. Go to the home screen of the phone to change the wallpaper

  3. Switch back to our activity, the activity restarts.

It seems it is related to the Material You theming.

I would like to disable the restarting of activity when my app comes to the foreground. Is there a way?

Answer

It is a non-traditional configuration change. By “non-traditional”, I mean that it cannot be blocked by android:configChanges — your activity will be destroyed and recreated whether you like it or not.

If you have Configuration objects from before and after the change, you can determine that this scenario occurred by calling diff() on the newer Configuration to compare it to the older one:

val diff = resources.configuration.diff(vm.originalConfiguration)

Log.d("WallpaperCCTest", "matches CONFIG_ASSETS_PATHS? ${(diff.toLong() and 0x80000000) != 0L}")

Here, vm.originalConfiguration points to the older Configuration, and we get the current Configuration from the Resources object. (diff.toLong() and 0x80000000) != 0L will evaluate to true if a wallpaper change or something similar triggered the configuration change. There are other edge cases for this — this whole “unblockable configuration change” thing came about when Sony got Google to add support for runtime resource overlays (RROs) back in 2017. So, some of those “change the system theme” apps might trigger this same unblockable configuration change.

As Nguyễn Hoài Nam notes, you can detect this from onConfigurationChanged() of a custom Application. Or, have your viewmodel hold onto the previous Configuration and compare it with the current one in onCreate() of your activity.

I have more on this issue in this blog post. AFAIK, there is no way to opt out of this configuration change, so if your app was designed to avoid configuration changes, you may be out of luck.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..