Number Of Times The Service Has Run
Solution 1:
if you are starting service with startService
then for first time it's onCreate
method will be called and it does not matter how many times you have started the service but its method onStartCommand(Intent, int, int)
will be called with respect to your startService call. Service stops when you call stopService
irrespective of how many times you have called startService
.
Don't forget to release the resources, threads when you stop the servive.
you can refer this doc:
http://developer.android.com/reference/android/app/Service.html
Solution 2:
If an Android service is already started, Android will not start the service again. For example calling:
Intent intent = newIntent(YourService.class.getName());
startService(intent);
...in several separate activities (for binding to IPC listeners or whatnot), will not create new instances of the service. You can see this by looking at your DDMS, you should see something like:
com.domain.app
com.domain.app:remote
The remote entry is your service, and will only appear once, you can also see this under Android settings, applications, running services on your device.
As for data being erased when the service restarts, this is preserving state issue, any data you want to survive a restart (like killing the app) should be stored, see http://developer.android.com/guide/topics/data/data-storage.html for more detail.
Solution 3:
You can easily check if a service is running with the following code
public boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.app.ServiceClassName".equals(service.service.getClassName())) {
returntrue;
}
}
returnfalse;
}
You can also read more about the lifecycle of a service here: http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle
Post a Comment for "Number Of Times The Service Has Run"