I have a application in which I have a UART (Serial Comms) to service and several other "tasks" that require separate worker threads to keep the UI responsive. My problem is in understanding when/where I should create these threads and when they get terminated. Currently, I am creating them in the OnCreate() of the main UI Activity. But, this is causing havok, as I recently needed to "jump" from one Activity back to the Main activity. The recommendation was to use an Intent and StartActivity() with the appropriate flags to "clear to top". But, this of course causes a whole new set of instances for my threads, and everything unravels. Should I be using a Service, tied to my UI somehow? I have subclassed my Main Application, so I have the OnCreate() of my Application. I'm leaning towards that, but can't seem to grasp the life cycle of the Application versus the Activities.
Use a service. You have an ongoing task that isn't inherently attached to one particular activity.
You can start a long running task with startService
and the service will not be killed until it's finished. Meanwhile, Context#bindService
will keep the service alive as long as anything is bound to it.