Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to create a background process service that will run whether or not the app created it is still running?

So, I want my app to create a Service that will initially run in the background and do some stuff. This background process will never stop. It will constantly keep running. The ONLY way the background process can be created or destroyed would be through the app. I understand that there are endless possibilities to kill a process. I guess I want my app to be able to tell me whether or not the process is running and retrieve real time information from that process. Along with that, be able to start and/or destroy the background process.

So, let's say that you were to open the app and start/create the service. Even when you close/terminal/call onDestroy for the app, I still want the background process to be running. The only way to destroy this service would be to re-open/re-create the app, and destroy it.

Does Android allow something like this? Is there a way to get around this?

I was going to create a IntentService and make it run an infinite loop. Though, my only problem is how to obtain information from the IntentService. From what I've learned, an IntentService is created and kills itself when it's done.

I'm still new to Android, so don't hesitate to be specific and/or remedial.

like image 527
Rob Avery IV Avatar asked Feb 14 '23 13:02

Rob Avery IV


1 Answers

Answer is quite simple.

  • Create a Service (not IntentService, just a simple Service) and start it from your activity. IntentService will not work in your case as it will call stopSelf() on itself as soon as you return from onHandleIntent()
  • Your service will continue to run till somebody explicitly calls stop method on it or service itself calls stopSelf() method. But in low memory conditions, platform can kill your background services. When device has enough memory platform will restart your service provided you make your service STICKY by returning START_STICKY in onStartCommand().
  • call stopService() from your activity when required. It doesn't matter even if your activity got stopped/killed and restarted.
  • You dont really require to launch your service in another process. Because platform will make sure to start and keep your application process alive as long as any of its entities (Activities, Services, Receivers) are alive. Dont worry, your application will not appear in running apps list if your process is running but none of its activities are alive.

Hope this answers your question.

like image 55
Santosh Avatar answered Mar 10 '23 10:03

Santosh