0

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?

Simson
  • 3,373
  • 2
  • 24
  • 38

2 Answers2

3

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.

Sujan Poudel
  • 794
  • 5
  • 16
1

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

Christilyn Arjona
  • 2,173
  • 3
  • 13
  • 20