Search code examples
kotlinandroid-notifications

How to make it go to the main screen only when you allow notification access in Kotlin


I want the app to run like this:

When you run the app, you go to the window to set the notification access right, and if you go back while allowing access to the app, you go to the main screen. and when notification access right is not granted, you go to notification access window until right granted.

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val notificationManager =
            this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= 23) {
            if (!notificationManager.isNotificationPolicyAccessGranted) {
                this.startActivity(Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS))
            }
        }
    }

The code is written as above, but regardless of whether the notification permission is allowed or not, if you go back, you will be taken to the main page.

How can I modify my code so that I can navigate to the main page only when permission is granted?


Solution

  • Use this code in MainActivity.kt

    if (!isNotificationListenerEnabled(this, WhatsAppService::class.java)) {
                val enableNotificationListenerIntent = Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS)
                startActivity(enableNotificationListenerIntent)
            }    
    
    
    
    private fun isNotificationListenerEnabled(context: Context, listenerService: Class<*>): Boolean {
            val flat = Settings.Secure.getString(
                context.contentResolver,
                "enabled_notification_listeners"
            )
            return flat?.contains(listenerService.name) == true
        }