Home > Net >  Android Kotlin registerForActivityResult no callback
Android Kotlin registerForActivityResult no callback

Time:02-03

In Android 13, I need a basic flow to get permission for push notifications:

class MainActivity : ComponentActivity(), LocationListener {
    val notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
        if (isGranted) {
            // Permission is granted. Continue the action or workflow in your
            // app.
        } else {
            // Explain to the user that the feature is unavailable because the
            // feature requires a permission that the user has denied. At the
            // same time, respect the user's decision. Don't link to system
            // settings in an effort to convince the user to change their
            // decision.
        }
    }

    private fun requestPushNotificationPermissions(){
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED)) {
            // granted
        }else {
            // not granted, ask for permission
            notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
        }
    }
}

This is what happened:

  • when user first installed the app, checkSelfPermission returns not granted, and we then lauch permission launcher
  • user sees the permission dialog in Android 13
  • user selects Allow
  • Expected: registerForActivityResult callback will be fired with isGranted true
  • Actual: registerForActivityResult callback is not fired.

Same if user selects Not Allow. callback is never fired. Why?

This is my dependencies:

implementation 'androidx.activity:activity-ktx:1.2.0-alpha07'
implementation 'androidx.fragment:fragment-ktx:1.3.0-alpha07'

CodePudding user response:

sadly can't help why it doesn't work. But I used EasyPermission for handling the permissons request and it works fine. https://github.com/googlesamples/easypermissions

CodePudding user response:

Turns out, the registerForActivityResult callback never fires, because somewhere in the Activity, there is this piece of old function "onRequestPermissionsResult" that is accidentally catching all permissions callback:

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {        
    if (requestCode == locationPermissionCode) {
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Location permission granted
        }
        else {
            //Location permission denied
        }
    }else{
        //Notification permission callback accidentally landed here silently        
    }
}

Hope this helps someone.

  • Related