-
Notifications
You must be signed in to change notification settings - Fork 44
LifecycleOwner and askNotificationPermission #161
Description
I encountered the following crash for android:
Process: pl.flashcards.ev.android.dev, PID: 7646
java.lang.IllegalStateException: LifecycleOwner pl.flashcards.ev.MainActivity@612ff7 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
This happens if you use:
val permissionUtil by permissionUtil()
permissionUtil.askNotificationPermission()and call askNotificationPermission() outside of onCreate.
The reason is that the permission launcher must be registered before the LifecycleOwner reaches the STARTED state. However, in real scenarios we often want to request notification permission only after some user interaction (for example, after showing an explanation).
It would be good to mention this explicitly in the tutorial.
The recommended approach is to initialize the permission utility in onCreate:
androidPermissionUtil =
AndroidPermissionUtil(contextFactory.getActivity() as ComponentActivity)Then, later—wherever it makes sense (for example, in a button click handler)—you can safely request the permission:
androidPermissionUtil?.askNotificationPermission()This way, the launcher is registered at the correct lifecycle phase, but the permission request itself can still be triggered by user interaction.