How to open notification access settings for my app, programmatically?


What Kotlin code could I use to open notification access settings programmatically, making sure that the settings for my app are selected automatically, instead of getting a list of apps and forcing the user to choose?

-1
Sep 16 at 10:04 AM
User AvatarAngel
#android#kotlin#android-notifications

Accepted Answer

For opening your app's notification access settings you can use this Kotlin function:

fun openNotificationAccessSettings(context: Context) { try { var intent: Intent? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS) .putExtra( Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME, ComponentName(context, NotificationListener::class.java).flattenToString() ) } else { intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS) } val value = "${context.packageName}/${NotificationListener::class.java}" val key = ":settings:fragment_args_key" intent.putExtra(key, value) intent.putExtra(":settings:show_fragment_args", Bundle().also { it.putString(key, value) }) context.startActivity(intent) } catch (_: Exception) {} }

Replace NotificationListener with your notification listener service class name.

Make sure the service is added in AndroidManifest.xml, for example:

<service
    android:name=".NotificationListener"
    android:enabled="true"
    android:exported="true"
    android:label="NotificationListener"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
    android:foregroundServiceType="connectedDevice">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>
User AvatarAngel
Sep 16 at 10:04 AM
2