Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a thread in the background after the app is killed

Tags:

android

I want to provide the user with toast notifications every 'x' minutes, I tried to do this with the help of service, but when the application was killed, the service stops. The same issue occurs with intent Service as well, what should I be doing in order for me to keep a thread/service in memory even after the application is killed?

like image 275
Dwarakesh Pallagolla Avatar asked Apr 11 '14 08:04

Dwarakesh Pallagolla


1 Answers

The terms of your question are a bit confusing :

  • the application lies in a process. If the process is killed, then everything running in that process is killed.
  • if you want something to survive that process's death, you should use a second process and run the thing to survive inside it.
  • a service can be run in its own process, looks like a good choice here. Look at android:process attribute in the service tag : http://developer.android.com/guide/topics/manifest/service-element.html

But what you want to do is maybe simpler : set a repeating task. For this, you could use the alarm manager.

You can, for instance :

  • provide the alarm manager with a pending intent
  • the pending intent will trigger a service of your own
  • the service will we waked up, then run. This has the advantage of not letting your service always run and count time to know when it has to wake up (which would drain battery). Here the alarm manager will wake it up when needed, your service will just execute its task and die.

If you combine this approach with the first part of that answer, running your service in a different process, then you can achieve something that's really light weight for the Android device : only your service (in its own process) will wake up at given interval, and the application's process will not be launched by this alarm, but only the service's process.

And about toast notifications, yes, a service is a good place to do it, but the notification bar may be more appropriate to display notifications and notify the user that some event took place inside a background service.

like image 117
Snicolas Avatar answered Oct 04 '22 11:10

Snicolas