Android Foreground Service() issue

157 views Asked by At

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()
  }
}
1

There are 1 answers

2
Václav Hodek On BEST ANSWER
  1. Why don't you initialize mWindowManager in assigment?

private val mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager

  1. If you need to use lateinit var, you should check for initialization state:

if (::mWindowManager.isInitialized) mWindowManager.removeView(mFloatingView)

  1. Having any logic in onDestroy() for services is not recommended as you can't be sure it's called.

  2. You don't need to remove views as they are removed automatically when the service is finished/killed.

  3. 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), you onStartCommand is not called.