I am developing an application in which a background service is created to collect sensor data. I am starting the service from my activity:
startService(new Intent(this, MyService.class));
I created the service so if the application is destroyed, the background service still continues to collect data. I tried this, and it worked to a certain extent. My problem is that when I kill the application, the service seems to restart because the onCreate() service and the onStart() methods are invoked. Is there any way with which the service isn't restarted please?
UPDATE:
As suggested in an answer below, I added the following method in the service but no luck.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
It depends on the value returned in onStartCommand.
You must return START_NOT_STICKY
According to the documentation:
For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them
In short:
If you return START_STICKY the service gets recreated whenever the resources are available. If you return START_NOT_STICKY you have to re-activate the service sending a new intent.
Since all of this triggered my curiosity, I made a sample app to test this. You can find the zip with all the sources here
There are a startService button and a stopService button that do what you would expect from them.
The service returns START_NOT_STICKY in onStartCommand.
I placed toasts in onCreate, onStartCommand and onDestroy.
Here what happens:
If I press start, onCreate and onStart are called
If I press stop, onDestroy is triggered
If I press start twice, onCreate is called once and onStartCommand twice
So it behaves as one would expect.
If I start the service and kill the app as you described, onDestroy does not get called but neither onCreate or onStart.
If I get back to the app and I press start again, onCreate gets called which means that, as I wrote before, START_NOT_STICKY prevents the service to getting restarted automatically.
I guess you have something else in your app that starts the service again (maybe a pending intent).
The app and the service live on the same process, which means when the app is killed so is your service. Changing the return value of onStartCommand doesn't affect this process. It simply tells the Service to either start/stop when you tell it or when it's finished doing what it needs to. As mentioned in your comment to your original post, setting it as a foreground process worked, but that's really just forcing the service to have a high priority, not solving the problem.
To change the Service so that it's killed separately and assuming it's a started service rather than a bound service due to the use of onStartCommand, specify a process name in the manifest for that Service.
From the Process and Threads Developer Guide:
The manifest entry for each type of component element— <activity>, <service>, <receiver>, and <provider>—
supports an android:process attribute that can specify a
process in which that component should run. You can set
this
attribute so that each component runs in its own process or so
that some components share a process while
others do not. You can also set android:process so that
components of different applications run in the same
process—provided that the applications share the same
Linux user ID and are signed with the same certificates.
Android might decide to shut down a process at some
point, when memory is low and required by other
processes that are more immediately serving the user.
Application components running in the process that's
killed are consequently destroyed. A process is started
again for those components when there's again work for them to do.
From <service> in Manifest File:
android:process
The name of the process where the service is to run.
Normally, all components of an application run in the default process
created for the application. It has the same name as the application
package. The element's process attribute can set a
different default for all components. But component can override the
default with its own process attribute, allowing you to spread your
application across multiple processes.
If the name assigned to this
attribute begins with a colon (':'), a new process, private to the
application, is created when it's needed and the service runs in that
process. If the process name begins with a lowercase character, the
service will run in a global process of that name, provided that it
has permission to do so. This allows components in different
applications to share a process, reducing resource usage.
Not sure why the other answer that mentioned this was down voted. I've used this method in the past and, today, created a simple one Activity app with a Service on a different process just to make sure I wasn't crazy. I used Android Device Monitor to kill the app's process. You can see both, separate processes in ADM and can see that when the app's process is killed, the Service's is not.
Start not sticky doesn't work above kitkat, and the other onTaskRemoved not working above Marshmellow.
onTaskRemoved could be used by handled some exceptions. Did not worked on that. But try that one.
If you are using an IntentService, it has an
onHandleIntent()
method where you should place the code that needs to be executed. It is executed in a separate thread (not a UI thread where your application runs) therefore your app shouldn't affect it. When the code has finished executing, the thread is terminated and the service is stopped automatically.
I ran into the same problem and was able to resolve it by making the service run in a global process. You do this by adding the following to the manifest tag:
process="com.myapp.ProcessName"
(Make up whatever name.)
When I did this I found that my service wasn't killed (and restarted) when the app is swiped off the list. Presumably this is because the app process is killed when you swipe it off, but global service processes are not.
The disadvantage of this is that communication between your app and service now has to be via the IBinder interface; you can't directly call functions in the application or service from the other one, because they're running in different processes.
I know its much late to answer this question, but may be it can be helpful to others. This really helped me for my Music Player App.
If there are services which can be disruptive or can affect the user experience like music etc , then in that case you have to use Notification and when service is started successfully, then create the Notification and use the function
startForeground(int Notification_id,Notification);
This will run your service in background without restarting and reinvoking its methods
https://developer.android.com/reference/android/app/Service.html
Related
I have an Android Library with a service, which I implemented using AIDL. I want a single instance, cross application to be used with other apps. So I have a base app with the service and I managed to make the library for other apps to use the same instance.
My problem comes when I close all apps using the service, because for every app, the on destroy unbinds from the service, but the service is still running.
Also, I'm only using the service by binding, not by startService().
I checked through android studio that the service is running after closing the apps, and the counter I have on the service for each bind/unbind call is 0!. I increment the counter when there is a call to bind, and decrease for calls to unbind. My only way to make the service stop is by opening the base app, which has the service defined and closing it.
Edit: Also noticed that onBind is being called only once, even for other apps that are binding, but the reference for all those apps is still the same service, they share the same information and only one Service is shown in the android studio.
Edit: I've also observed that if one of the apps using the service is the base app, if I close it, the service dies and another one is started, the other apps don't notice the change, they keep using the service as if nothing happened, which is understandable because it's a remote service.
What is happening and what can I do about it?
For the two points being questioned:
I was able to verify what CommonsWare said that the process in which the service is run is still up, but the service itself is not. At first I had a thread running in the service after every app unbound, but after making sure it wasn't up in the end made the service be destroyed.
The second issue, regarding the service being destroyed while still bound with other activities was solved by seeing this link which describes a bug in android that kills services when it shouldn't. My case was simply solved by making my service run in the foreground, which I didn't know was possible.
After some tests I verified the service is still intact as long as any app is bound with it, and that the service indeed is destroyed correctly after no more app is bound.
when I open the activity of my project I call the startService(Intent intent) method to start a new Service.
When the activity is destroyed the service shouldn't be killed (because I didn't use the bindService() method), but the fact is that when I close my activity the service is killed and after a second the system creates a new Service (I verified that, the system calls again the onCreate() method of my service). What do I have to do to keep only one service ? Thank you
To have a service running independently of your application's main process and to be sure that Android does not kill it while it's doing something, there are two things you should do/try.
Run your service in a separate process. You can achieve this by adding the following attribute to your service declaration in the manifest:
android:process=":somenamehere"
When your service is running and you do not want it to be killed by the OS, you have to use the startForeground(int id, Notification notification) method. When the service finishes whatever is doing and can be killed by the OS, call stopForeground(boolean removeNotification). "startForeground" requires a notification as argument because every foreground service must display a notification so the user realizes about it
I hope this helps you.
I mean I hold the home button and then kill my activity from the list of app open
That does not "close" an activity. That terminates your process. The user is welcome to terminate your process whenever the user wants, whether via this means or through third-party task manager apps. There is nothing you can do about this -- you cannot stop the user from terminating your process. Since your process will stop for other reasons as well (e.g., sheer old age), you have plenty of reasons to handle this case.
Edit: Please refer to CommonsWare's answer
Old answer: You should override public int onStartCommand(Intent intent, int flags, int startId) method and return START_STICKY value as the mode of your service.
this will keeps your service working when the activity is destroyed or even when you exit your app unless you call stopService(Intent) explicitly
I have an Android app, in which Activities fire long running operations that run in the background. These operations interact with the Activities when done. I'm developing a component that handles the Activity/Long-Running-Task coupling, taking care of activities being destroyed and recreated.
Right now that component is implemented as an Android service. The activities call bindService and use the resulting IBinder to start and track tasks. I decided against using startService, because I prefer the richer API possible through a Java interface.
Now the problem. Activity A start ups, binds to the service and calls serviceApi.runTask(...). Activity A is then destroyed (because the user flips the phone, for instance) and recreated as Activity A'. A' then binds again to the service, announces its existence and everything should be running nicely.
Except that my Service gets destroyed. When Activity A is destroyed, it unbinds from the service. Android sees there are no more clients, and kills the service. When Activity A' is created, the service is created again, and I lose everything the old service had.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android? Is there a better design that fits this problem?
Editted: Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running. Android can kill sticky services if resources are low. Killing the service will cause the application to malfunction, and I can't have that.
Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running.
Correct.
Android can kill sticky services if resources are low.
Also correct. All "sticky" means is that Android might restart the service.
Killing the service will cause the application to malfunction, and I can't have that.
It is impossible to create a service that is guaranteed to run forever. For starters, users can get rid of your service whenever they want, because users detest developers who have pointless services that run forever. Writing everlasting services is necessary only in very few cases; otherwise, it's just sloppy programming.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android?
Singletons (a.k.a., static data members) will go away when the process is terminated. The process will be terminated eventually, particularly if there are no active services and none of your activities is in the foreground..
Call startService and in onStartCommand return START_STICKY. It should keep the service going.
You may also want to look into foreground services:
http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification)
Yo have to create persistent service. Refer to this manual.
In a few words - don't call bindService, call startService.
I'm developing an Android application that consists of:
a lightweight background service that logs events to a DB
a heavier GUI application that summarizes these events and displays graphs.
I'm having trouble creating the service part, though. The graphic application can use quite some RAM, and when it goes to the background, the OS closes it after some time of not being used.
The problem is, when the application gets shut down, so does the service. This is bad because this keeps me from recording further events. I don't care if the application gets terminated, but the service needs to keep on running.
I have tried numerous ways to keep the service alive, like having it use threads or a differently named process than the main app. Nothing has worked, and I have found no help on any of the android developer pages or forums.
Thank you for your advice!
Try to return START_STICKY in your service's onStartCommand(). Also how do you start your service? If you use bindService() with BIND_AUTO_CREATE flag it will be stopped automatically on unbindService(). You should explicitly start it with startService() and stop calling stopSelf(). Than OS keep your process running on the background after activity will be closed. Note: the activity and the service run in one process and it's imposible: "application gets terminated, but the service needs to keep on running". But it is possible to keep the process running without activities, with service running on the background.
Read the detailed info http://developer.android.com/reference/android/app/Service.html.
good luck!
You should use the AlarmManager to respawn your service. You just can't keep your service alive eternally.
Check about the lifecycle : http://developer.android.com/guide/topics/fundamentals.html
IIUC, there should only be one instance of a given Android service, it is a singleton.
However, my service gets instantiated multiple times, although I
do nothing for it.
When the service crashes (for example when I uninstall the app through adb), it
gets scheduled for restart ("Scheduling restart of crashed service.. "). I
understand this is an effect of the service being sticky.
After that, when my app starts, it calls startService() and bindService(), and
the service gets appropriately started and bound. But the service is then
reinstantiated and onCreate() is called repeatedly, as many times it was
scheduled for restart.
Each instance then wait for clients to bind and register, but onBind() is only
called in the "main" service instance. The additional instances wait a bit for
client to bind, and since that doesn't happen, they call stopSelf().
But stopSelf() has absolutely no effect in these "dead" instances, onDestroy()
is never called.
The "main" service instance does work as expected, and when it decides to call
stopSelf(), onDestroy() is indeed called.
Worse, all these dead instances accumulate, they never gets destroyed.
Therefore, their only possible end is a crash (which happen every time I
launch/install through adb), and thus scheduled restart.
So that in the end I get many of these dead instances, which are restarted
progressively once by minute approximately.
Does anyone know what's going on?
I got similar behavior if I use eclipse to restart an app with a remote service. According to logcat, system consider the killed service had a crash and tried to restart the service. At the same time, the service has been restarted with the restarted app. For some unknown reason, Android system does not realize there is already a running service, and tries to start a new one.
It happens several times on Optimus one, Galaxy tab, and EVO 3D. It is fine with Nexus one.
Because I haven't seen your code, this is just a guess: Maybe you have a memory leak that prevents the service from destroying properly. That's the only reason I could think of to get multiple instances of service. For example, if you service is holding on to some object that also have a reference to your service. It happens a lot with inner classes.
Check out this video from Google I/O to see if this problem applies to your services and how to find it: http://www.youtube.com/watch?v=_CruQY55HOk&feature=player_embedded
if you use the section to be excecuted in onstart() . if ur starting the service by onclick button or like clicking on icon multiple time means ,what it will do is if service is already running means ,it will go to onstart(),so the method is excecuting again and again its not that service is starting multiple times .... ur method is running for multiple time ,This i told accornding to my guess may be exact code will be Explaind properlly
if your app exit on crash or kill the process it belongs to like System.exit(), it will start after your app exit or start if your service is running in the same process with Application.
Because you kill the process, and Android detect your service should not stop, so Android restart it for you after your app exit. And why service start again after app restart, I think it is Android's bug, it reallocate a new process to your app instead of using the process allocate to your service.
So, how to solve this problem?
just set the attribute android:process=":background"(whatever you want here, starts with :) to your service node in AndroidManifest.xml. hope it helps you.