I have an interface:
interface PermissionLauncher<in T> {
fun bindLauncher(launcher: T)
fun updatePermissionsStatus()
}
And I implemented it for activities:
class BindLauncherException : IllegalAccessException(
"You must call bindLauncher method in your onCreate() function",
)
class ActivityPermissionLauncher :
PermissionLauncher<FragmentActivity>, LifecycleEventObserver {
private var _activity: FragmentActivity? = null
private val activity get() = _activity ?: throw BindLauncherException()
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when (event) {
Lifecycle.Event.ON_DESTROY -> {
activity.lifecycle.removeObserver(this)
_activity = null
}
else -> {
// No need to handle
}
}
}
override fun updatePermissionsStatus() {
// update permission status with the activity instance
}
override fun bindLauncher(launcher: FragmentActivity) {
_activity = launcher
activity.lifecycle.addObserver(this)
}
}
Now in my activities I use it like this:
class PrivacyAndTermActivity : FragmentActivity(),
PermissionLauncher<FragmentActivity> by ActivityPermissionLauncher() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bindLauncher(this)
myButton.setOnClickListener {
updatePermissionsStatus()
}
}
}
Now everything works fine in my test devices. but in crashlytics it seems that some devices are crashing with BindLauncherException.
I put that exception to inform the developer not to forget calling bindLauncher in onCreate function of delegated activity. But I don't know why even that I'm calling it in my onCreate some users still getting the error. Because I clear my activity instance only in onDestroy and it should be refill in onCreate again.