Simson
Simson

Reputation: 3559

Start a thread once and only once

I have one singleton object on which I would exactly one thread executing while the app is running.

So far I have created the thread in MainActiviy::onCreate

class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
     thread{myobject.run()}
   }
}

But contrary to the documentation where the arrow leading to onCreate() is App process is killed, it looks like onCreate() is called every time the app is restarted regardless of if being killed or if its threads were still running. flowchart

object myobject{
   fun run(){
      while(true){
         do_stuff()
      }
   }
}

It is of course possible to acquire a lock to only start the thread once, but since there is a nice syntax in Kotlin for singleton objects, and this is a related (I assume very common) problem I came to believe there maybe could be a simple more elegant way for this.

Or is the preferred way to acquire a lock on the object?

Upvotes: 0

Views: 406

Answers (2)

Sujan Poudel
Sujan Poudel

Reputation: 853

You can achieve this by starting the thread in OnCreate of your Application class. Make a class extending the Application class and add this class in your manifest

MyApp.kt

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
       thread{myobject.run()} //here
    }

}

AndroidManifest.xml

<application 
   android:name=".com.yourpakage.MyApp"
   android:label="@string/app_name" 
   ...>

Unlike the activity lifecycle Application's onCreate is called only once. So there will be only one thread throughout the life of your app.

Upvotes: 3

Christilyn Arjona
Christilyn Arjona

Reputation: 2283

You can use an IntentService and store the status on a SharedPreference. https://developer.android.com/training/run-background-service/create-service

Upvotes: 1

Related Questions