I have three activities in my app and all those activities requires access to service. 开发者_如何学编程So if i start the service three times will it be started three times or only once. And if once will the previous data be erased when service is restarted.
Thanx
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
If an Android service is already started, Android will not start the service again. For example calling:
Intent intent = new Intent(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.
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())) {
return true;
}
}
return false;
}
You can also read more about the lifecycle of a service here: http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle
精彩评论