fix(android): Prevent crash in onDestroy #372
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR resolves a critical
UninitializedPropertyAccessExceptionthat occurs when theForegroundServiceis destroyed by the Android OS before theforegroundTaskOptionsproperty has been initialized.Under certain conditions (e.g., the system reclaiming resources while the app is in the background),
onDestroy()can be called withoutonStartCommand()having run, leading to a crash as thelateinitproperty is accessed before it has a value.The Fix
The solution is to add a defensive, idiomatic Kotlin check (
::foregroundTaskOptions.isInitialized) before accessing the property in theonDestroymethod. This ensures the app does not crash in this edge case and safely skips the auto-restart logic when the service's options were never loaded.Verification
This change is a standard, low-risk solution for this common Android/Kotlin lifecycle issue.
foregroundTaskOptionsis initialized, the behavior is unchanged.This directly addresses the root cause of the crash reports related to
lateinit property foregroundTaskOptions has not been initialized.