Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Service Stops When App Is Closed

I am starting a service from my main Android activity as follows:

final Context context = base.getApplicationContext(); final Intent intent = new Intent(context, MyService.class); startService(intent); 

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?

like image 732
Bam Avatar asked May 20 '13 13:05

Bam


People also ask

How stop service when app is killed android?

First, the easiest way to do what you're trying to do is to launch an Android Broadcast when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart after that. Dear Dr Sabri Allani, If your Service is started by your app then actually your service is running on main process.

How do I run background services on android?

This example demonstrates how do I run an android service always in background. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


2 Answers

I'm in the same situation, so far I learned when the app is closed the service get closed also because they are in a one thread, so the service should be on another thread in order fot it not to be closed, look into that and look into keeping the service alive with alarm manager here an example http://www.vogella.com/articles/AndroidServices/article.html this way your service won't be shown in notification.

lastly, after all the research I've done I'm coming to realize that the best choice for a long running service is startForeground(), because it is made for that and the system actually deals with your service well.

like image 85
3lomahmed Avatar answered Sep 18 '22 12:09

3lomahmed


make you service like this in your Mainifest

 <service             android:name=".sys.service.youservice"             android:exported="true"         android:process=":ServiceProcess" /> 

then your service will run on other process named ServiceProcess


if you want make your service never die :

  1. onStartCommand() return START_STICKY

  2. onDestroy() -> startself

  3. create a Deamon service

  4. jin -> create a Native Deamon process, you can find some open-source projects on github

  5. startForeground() , there is a way to startForeground without Notification ,google it

like image 33
alanban Avatar answered Sep 20 '22 12:09

alanban