How to run background function when device theme is changed(Dark mode on or off) on Android. Is there any onThemeChangeListener(OnDarkModeOn) or IntentFilter or BroadcastReceiver for it?
Asked
Active
Viewed 699 times
2
-
If you have no visible app, then why do you so desperately need to act in reaction to a user changing the theme? What do you possibly need to do that is so urgent you need to do it "now"? If your answer is "i want to download assets", then imagine if all apps did this... You should either check when your app is no longer in the background, have a foreground service, or use WorkManager to schedule a periodic check. – Martin Marconcini Jun 28 '21 at 15:56
1 Answers
1
I'm not sure that such listener is existing. But you can check you onConfigurationChanged
method:
add to the activity in your manifest file:
android:configChanges="uiMode"
And when onConfigurationChanged
method will be triggered you can check new Configuration
.
As it's described in the documentation: https://developer.android.com/guide/topics/ui/look-and-feel/darktheme#config-changes
This solution will not be working when app is in the background. But you can try to use Service
's onConfigurationChanged
method. But it looks like a big workaround and also in this case you should be aware about Background execution limit.

Anatolii Chub
- 1,228
- 1
- 4
- 14
-
will OnConfigurationChanged Method will run in background after app is killed?? – Shakir Kasmani Jun 28 '21 at 10:45
-
-
I tried to logs onConfigurationChanged method in the service and it works in my case, even when I killed the app. But since android O - background service is not a respective solution because of background execution limit, you can find more details here: https://developer.android.com/about/versions/oreo/background#services However you can use foreground service for this purposes. But in my opinion it looks like a big workaround. – Anatolii Chub Jun 28 '21 at 15:23