Is it possible for my Android App to be notified when an Android user setting has been updated?

Viewed 24

My app does not work without Notification Access, and I want to display a warning when it is on or off.

Is there a way I can monitor this setting without just polling it? Like is there something I can subscribe to that will automatically update me what this setting is changed?

I have tried the following code, but it is not updated when I update the setting.

var contentResolver = getContentResolver();
        val setting = Settings.System.getUriFor(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
        val observer: ContentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
            override fun onChange(selfChange: Boolean) {
                super.onChange(selfChange)
            }

            override fun deliverSelfNotifications(): Boolean {
                return true
            }
        }

        contentResolver.registerContentObserver(setting, false, observer);
1 Answers

Since you're requiring Notification Access, then you have a class that extends NotificationListenerService. You just need to override onListenerConnected() -- it only gets called once the ListenerService is connected, and that only happens when Notification Access is approved.

class ListenerService: NotificationListenerService() {
    ...
    override fun onListenerConnected() {
        super.onListenerConnected()
        // if you get here, then Notification Access was approved
    }
    ...
}
Related