registerForActivityResult callback is not triggered after moving permission handling from Activity to Fragment [closed]

4 days ago 1
ARTICLE AD BOX

PROBLEM

I am trying to migrate permission management from MainActivity to Fragment. I am having trouble opening the camera correctly after approving permissions.

REPRODUCTION

When I click for the first time, the console displays the log "noPermission", but after clicking Allow, nothing happens (the same when I click Deny), although after clicking a second time, the camera starts up and I get the log "hasPermission".

Fragment code:

private const val PERMISSION = Manifest.permission.CAMERA // inside onViewCreated() ViewModel.visibleFabs.observe(viewLifecycleOwner) { items -> fabMenuView.submitItems(items) { item -> when (item) { is FabItem.Camera -> fabClick() ... } } } private fun fabClick() { if (requireContext().hasPermission(PERMISSION)) { Log.d("Church permission", "hasPermission") onTrailCameraFabClick() } else { Log.d("Church permission", "noPermission") requestPermissionLauncher.launch(PERMISSION) } } fun Context.hasPermission(permission: String) = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED

DEPENDECIES

I have added the camera permission to the AndroidManifest.xml I add this packages:"androidx.activity:activity-ktx:1.8.2" and implementation "androidx.fragment:fragment-ktx:1.6.2"

I've seen some similar problems on the Stack, but without clear solution, so I'm sending it.

Read Entire Article