简体   繁体   中英

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. 流程图

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM