3

In the onStartCommand() method of my service, I start a long-running thread.

The service is started in my MainActivity's onCreate().

When my application quit (the time Main Activity closed by user), I stop the service. But I want to ensure that the thread mentioned before has been killed, or I have to stop the thread before/after that.

So will all threads started in a service be killed automatically when the service stopped?

kbridge4096
  • 901
  • 1
  • 11
  • 22
  • 2
    No they won't be killed. If you want to manually kill it you have to have some check points. Refer Async Tasks. – Malith Lakshan Jun 13 '16 at 14:45
  • 1
    Do a Log.d() inside the long running thread you would find out for yourself ! – Sourav Kanta Jun 13 '16 at 14:46
  • 2
    Threads are component independant. By component I mean Activity, Service, Content Providers and Broadcast Receivers. By independant, I mean they are not responding to lifecycle callback method such as onCreate, onDestroy, etc. – Alexandre Martin Jun 13 '16 at 14:48
  • So I wonder is it necessary to wrap a daemon thread (or a thread works like a daemon) in a service, and why? @AlexandreMartin – kbridge4096 Jun 13 '16 at 14:54

2 Answers2

0

I have just checked this by logging the thread's state in my service's onDestroy(). The thread remains alive after my service stopped.

kbridge4096
  • 901
  • 1
  • 11
  • 22
0
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
     super.onStartCommand(intent, flags, startId)
    Log.d(TAG,"Service started..")

    Thread(Runnable {
        for (i in 1..1000){
            Thread.sleep(3000)
            serviceRandom = i;
            Log.d(TAG,"Service Random - "+serviceRandom)
        }
    }).start()

    return Service.START_STICKY
}

This is a simple way to find out if thread keeps alive or stops after service stopped by calling

stopService(serviceIntent)

from Activity.

in logcat you will observe count incrementing logs. That means we have to stop it on our own.

Parmeshwar C
  • 979
  • 1
  • 12
  • 22