The mWindowManager
is throwing error in the onDestroy
addressing lateinit property mWindowManager has not been initialized
. But clearly it has been initialized inside onStartCommand
.
I am starting this foreground service from an activity which is then destroyed. So this service run on its own. And when the user want to destroy the service he/she has to open the app and destroy it from the activity. This issue is only coming from some devices and i am confused what is causing this error. Can anyone help me with it?
class PremiumService : BaseService(), View.OnClickListener {
private lateinit var mWindowManager: WindowManager
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
mWindowManager.addView(mFloatingView, params)
return START_STICKY
}
override fun onDestroy() {
mWindowManager.removeView(mFloatingView)
super.onDestroy()
}
}
private val mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
if (::mWindowManager.isInitialized) mWindowManager.removeView(mFloatingView)
Having any logic in
onDestroy()
for services is not recommended as you can't be sure it's called.You don't need to remove views as they are removed automatically when the service is finished/killed.
I wrote a few articles about floating windows on Android. As the author of Floating Apps, I know a bit about it and believe me, weird and absolutely unpredictable behavior is normal for some devices.
Explanation of your problem:
Your service may be, under some circumstances (not enough memory, etc.) restarted and as you don't want redelivery (you only have
START_STICK
), youonStartCommand
is not called.