I'm working on permissions util and I need to check for the permissions inside the class, here is my code:
class PermissionUtils private constructor(private val fragment: Fragment, private val context: Context) {
private lateinit var callBack: PermissionsListenerCallback
fun requestPermission(@NonNull permission: String, callBack: PermissionsListenerCallback) {
this.callBack = callBack
if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) this.callBack.onPermissionGranted()
else requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
private val requestPermissionLauncher = fragment.registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) this.callBack.onPermissionGranted() else showPermissionsDialog()//show customize dialog
}
interface PermissionsListenerCallback {
fun onPermissionGranted()
fun onPermissionDialogCancel()
}
}
And after I call requestPermission() I got this error:
Fragment XXX{90e0f42} (046e95ee-443b-4938-ad43-a02f42a90736 id=0x7f0a0310) is attempting to registerForActivityResult after being created. Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).
Any one can help please.