Android Periodic Background Services - android

I have a doubt that if i start a periodic service using alarm manager and start the service from the onCreate method of an activity. How can i prevent the service from triggering multiple times if that activity is launched again and again.

Assuming that you are creating a Normal Service (and not an IntentService), as per the Android Service documentation, when app invokes startService call, service will be instantiated and started (creating a process for it if needed).
Also, if it is running then it remains running.
So, to put it in simple terms,
Life cycle of "Started" service is independent of the life cycle of
Activity which has started this service. This is true irrespective
weather both are running in same process or different processes
So even though your Activity may be getting created multiple times, and if Service you created earlier is still running, then service object that already exists will be reused.
However, if there is a call to startService() from onCreate() of an Activity, this will invoke each time onStartCommand().
Hence, you need to ensure that you have a appropriate code/logic to handle multiple invocations of onStartCommand()

As far as I understood you must do something in either onCreate/onStart and onStop or onResume and onPaused. By do something I mean, in onCreate create what you need, alarm manager, etc then in onStart you can start the service and in onStop you stop the service or unBind from it, in case you want a foreground service. or in onResume or onStop.
Take a look here:
https://github.com/toaderandrei/live_tracking/blob/master/app/src/main/java/com/ant/track/activities/ServiceConnectActivity.java.
It is a tracking app that is based on MyTracks app from google.

Related

Service Stops Logging On Activity Destroy

I am trying to run a service in the background, despite the lifecycle state of the Activity that creates it. To guarantee it's running, the service (in addition to the services it performs) also has a thread that logs once a second. Finally, it also has logs in onStartCommand and onDestroy.
I'm starting the service with startService() and then I bind to it. My understanding is that this should keep the service running, regardless of what happens to its creator Activity. However, if the Activity is destroyed, the service stops logging. If the Activity is simply paused, there is no problem.
The following is also true:
1) onDestroy is never called on the service
2) I never call stopService or stopSelf after calling startService
I'm trying to figure out why the service is dying (there are no exceptions) or at the very least why it's being paused and no longer logging.
A bound service typically lives only while it serves application component and does not run in the background indefinitely.
http://developer.android.com/guide/components/services.html
http://developer.android.com/guide/components/bound-services.html
Use syncadapter instead of service . if you want to transfer data between server and client .
http://developer.android.com/training/sync-adapters/creating-sync-adapter.html

Is it necessary to check already running service list before starting or stoping a service?

while going through a code I found that before starting or stopping a service
a check was placed to confirm whether the service is already running or already stopped.
This was done using Activity Manager which gives information
about already running services in the System.
I want to know is this check necessary ?
what would happen if I call startService() for an already running service ?
What would happen if I call stopService() for an already stopped service ?
As it is mentioned in the Android docs
Note that multiple calls to Context.startService() do not nest (though
they do result in multiple corresponding calls to onStartCommand()),
so no matter how many times it is started a service will be stopped
once Context.stopService() or stopSelf() is called; however, services
can use their stopSelf(int) method to ensure the service is not
stopped until started intents have been processed.
So on your question
what would happen if I call startService() for an already running service ?
The onStartCommand() is called again and again but service once started cannot be started again or nested
What would happen if I call stopService() for an already stopped
service ?
When you call it first the onDestroy() method is called and later calls are ignored as service doesnt exist any more
If the service running, it does not create another instance, but onStartCommand() is still called on the existing instance.
You may look into Service Life cycle for more details.
Note that multiple calls to Context.startService() do not nest (though
they do result in multiple corresponding calls to onStartCommand()),
so no matter how many times it is started a service will be stopped
once Context.stopService() or stopSelf() is called; however, services
can use their stopSelf(int) method to ensure the service is not
stopped until started intents have been processed.
As for stopService, it wont affect anything even if the service in question is not running in my knowledge.
A service will only run once, no matter how many times you call startService().
Calling stopService() will make no effect on an already stopped service.Its like calling onDestroy() on a already destroyed Activity.

Android Service : What happen at the end of Activity life?

Suppose that Activity A starts Service S and binds to Service S.
What will happen to S when A is destroyed?
How can I recreate another Activity that binds to S? The sample code in http://developer.android.com/guide/components/bound-services.html unbind the service in onStop(). I think if I open the app again, a new process is created for another instance of A and S. But I want the new activity to get data from the old service.
What will happen to S when A is destroyed?
If A is the only Activity bound to S and you didn't start the Service via startService(Intent), S will be destroyed. That's because a Service will be alive till the last bound Activity unbounds from the Service. This is documented here.
How can I recreate another Activity that binds to S?
If A is bound and you switch to Activity B via Intent, the Service will be destroyed and recreated when B binds to it.
If you want the Service to be alive even if no Activity is bound to it, you have to call the Servie with startService(Intent). Now it will be around if you explicitly stop it or system means it's time to destroy it. If you don't want this behavior, persist your data and access it at given time.
I think if I open the app again, a new process is created for another instance of A and S
The process remains the same till the process is killed from the system or if you kill the process, which is not recommanded.
Edit:
Only the bound service lifecycle depends on Activities. If you want a stand alone one use startService(). This way it's independent from Activities and runs in background as long as the process of the App is up or you explicitly stop the Service with stopService() / stopSelf(). You could even have a Service in a own App and use IPC to communicate between Apps. It's all a matter of the use case.
As you can see the configuration of a Service is very flexible and you have to decide which fits best for your App.
If You start service through startService() it will keep remaining after Activity finishes.
If You start service through bindService() it will live until last Activity unbounds from it.
Also if service is already started and you call startService() no new instance of service will be created, but in living service method onStartCommand() will be executed.
Almost same when you bind to living service, methon onBind() will be executed.

If android restarts a Service is onCreate called again?

From my little android knowledge I understand that android OS can kill my service under extreme memory conditions.
I have created a service that returns START_STICKY. The service is meant to run in background.
If android is about to kill my service, will it call onDestroy ?
And when it restarts it would it call onCreate ?
See here, the dev guide. http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle
onCreate() is only called when the process starts, which can either be the first time the service is running, or if it was killed on restarted, essentially this is called whenever it starts.
onStartCommand() is called whenever a client calls startService().
When a service is destroyed / completely stopped, Android is supposed to call onDestroy() on that service. I think it's possible for that to not happen (e.g. process is killed not through Android system). In the case of a bound service, this is when there are not more active client binders.
Edit: onCreate() Service starts; onStartCommand()someone uses service; onDestroy()Service is killed / stopped.
If someone calls Context.startService() then the system will retrieve
the service (creating it and calling its onCreate() method if needed)
and then call its onStartCommand(Intent, int, int) method with the
arguments supplied by the client
...
A service can be both started and have connections bound to it. In
such a case, the system will keep the service running as long as
either it is started or there are one or more connections to it with
the Context.BIND_AUTO_CREATE flag. Once neither of these situations
hold, the service's onDestroy() method is called and the service is
effectively terminated. All cleanup (stopping threads, unregistering
receivers) should be complete upon returning from onDestroy().
http://developer.android.com/reference/android/app/Service.html
EDIT: Quick answer. Yes to both questions

When should a Service be stopped

My android application starts a service in the onCreate() callback of a class that extends Application. The service performs some background tasks that are relevant to the user only while the application is running. For that reason I would like to close the service when the application's last activity is closed. I've tried to perform closing the service in the callback onTerminate() , but it never gets called . So what would be the best place where a service should be closed ?
Thanks !
An Android service, once started, will continue running until the Context.stopService() or stopSelf() is called.
There are various hooks you can use to stop the service using Context.stopService (the service itself, or an onDestroy()/onPause callback in one of the activities, or a button click).
It's true that Android does some resource management itself, but it can take a long time before Android decides to terminate your services. And a service that's running but not doing anything just consumes resources on the phone that other apps might need.
In your case, the onPause method of your last activity would be a good that will get called, and as such is the correct place to stop the service.
The onPause() callback will be made when your activity is paused for any reason, and you know that when this happens your app will not be visible again until onResume() is called. If your service has a reason to run in the use case that your activity might be started again soon, you should add an entry to your service that onPause() calls, to set a delayed service termination. In onResume() you can cancel that delayed termination through another entry.

Categories

Resources