Reputation: 1332
I created a service and want this service was always running. But when I close the application which created the service, Android removes the service, and then it restarts.
The service in my application is created by pressing the button in the MainActivity
as follows:
startService(new Intent(getApplicationContext(), MyService.class));
Logcat:
01-22 11:44:52.242 1218-1389/system_process I/ActivityManager﹕ Killing 2040:com.my.application/u0a10046: remove task 01-22 11:44:52.252 1218-1218/system_process W/ActivityManager﹕ Scheduling restart of crashed service com.my.application/.MyService in 5000ms 01-22 11:44:57.272 2061-2061/? D/dalvikvm﹕ Not late-enabling CheckJNI (already on) 01-22 11:44:57.272 1218-1235/system_process I/ActivityManager﹕ Start proc com.my.application for service com.my.application/.MyService : pid=2061 uid=10046 gids={50046, 1028}
Upvotes: 2
Views: 1124
Reputation: 95578
The behavour has changed several times with different Android versions. You can't prevent Android from killing your Service
in some cases. On some Android versions, it can help if you put your Service
in a separate process. Usually, when you swipe the app from the list of recent tasks, Android will then kill the process hosting your activities, but leave the process hosting your Service
. To do that, add
android:process=":service"
to the <service>
declaration in the manifest.
Be aware that you will now have 2 processes running, and that makes some things more complicated. If you have a custom Application
class, an instance of it will be created in EACH process. If you rely on static
variables, they are not shared across processes. This can make your life miserable if you don't understand what is going on.
Upvotes: 1
Reputation: 43
In your Service class, adding "return START_NOT_STICKY" as follow:
public int onStartCommand(Intent intent, int flags, int startId) {
// your code ...
return START_NOT_STICKY;
}
the meaning of START_NOT_STICKY is that (mentioned on the java doc of Service.java):
Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to startService() . The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.
Upvotes: 1