0

I'm just learning about the Services in Android .I have not used any stopService() function but I expect my service to stop working as soon as I kill the app(by closing it and removing it from recent screen) .That's not happening and my Log message continues to print.

This is the service class that I'm using

class NormalServiceClass : Service() {
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        thread {
            while (true) {
                Log.d("NORMALSERVICECLASS", "Service working")
                Log.d("NORMALSERVICECLASS", Thread.currentThread().name)
                Thread.sleep(2000)
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

}

I'm starting the service in my Activity using

startService(Intent(this,NormalServiceClass::class.java))

Why is that happening , Since its not a foreground service .

newbie_coder
  • 225
  • 2
  • 9
  • How do you actually kill an app? – khoben Feb 17 '22 at 06:48
  • I close it and remove it from recent screen. I tried the "Terminate application" option from logcat as well . – newbie_coder Feb 17 '22 at 06:52
  • `super.onStartCommand(intent, flags, startId)` returns `START_STICKY` which means the system is trying to restart your service, and if your target device is running an Android version below O, the service has a really good chance of recovering. – khoben Feb 17 '22 at 07:21

2 Answers2

0

Do you stop your service?

stopService(Intent(this,NormalServiceClass::class.java));
Evyatar Cohen
  • 292
  • 1
  • 9
  • 25
0

First of all, you're adding overhead to your system by making an infinite loop like this:

while (true) {

So, solve that error first and secondly to stop the service something like this should be enough.

stopSelfResult(startId)
return super.onStartCommand(intent, flags, startId)
Darkman
  • 2,941
  • 2
  • 9
  • 14