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?

7
  • I think you should start your thread in onCreate() of Application so there will be only one thread throughout the life of your app Dec 13, 2019 at 5:35
  • That is what I am doing but onCreate() is called when the user leaves and returns to the app so I get multiple threads
    – Simson
    Dec 13, 2019 at 5:37
  • 1
    You are doing this in onCreate of a activity I said do in onCreate of Application class stackoverflow.com/questions/18002227/… Dec 13, 2019 at 5:39
  • Please write this as an answer!
    – Simson
    Dec 13, 2019 at 5:45
  • Like this: medium.com/@balakrishnanpt/…
    – Simson
    Dec 13, 2019 at 5:52

2 Answers 2

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.

1

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.