问题
I have a background service, and I am doing all the operations on this service.
The service is working with activities at times. But if the application closes, the service restart with START_STICKY; It works correctly, but sometimes it takes a long time to restart, like more than a minute.
@Override
public void onCreate() {
SocketIOConnect();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
How do I reduce the restart time?
回答1:
How do I reduce restart time?
You do not control this. It is up to the OS to determine when it will restart services whose processes were terminated for one reason or another.
Bear in mind that your service might never restart, if the user force-stopped your app (e.g., from Settings).
回答2:
You cannot control that. But however, I could suggest some good practices.
- You should call the
super.onCreate();first before calling other methods inside youroverridedmethod. - If your
service classisextendedfromIntentService class, and if you decide to alsooverrideother callback methods, such asonCreate(),onStartCommand(), oronDestroy(), be sure to call thesuperimplementation, so that theIntentServicecan properly handle the life of the worker thread. check from android developer side
You can call the super.onStartCommand() as follows:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, START_STICKY, startId);
return START_STICKY;
}
- The constant variable
START_STICKYwill let the service run indefinitely until you explicitly callstopService()orstopSelf(). Therefore, make sure that you have the option to stop it, otherwise you have to force stop it from Application Settings. - You can add a category TAG to your service before starting so then you can use that TAG to uniquely identify and stop the service externally by calling
stopService()method.
Starting service
serviceIntent = new Intent(MainActivity.this, MyService.class);
serviceIntent.addCategory(MYTAG);
startService(serviceIntent);
Stopping service
serviceIntent = new Intent(MainActivity.this, MyService.class);
serviceIntent.addCategory(MYTAG);
stopService(serviceIntent);
来源:https://stackoverflow.com/questions/25569329/why-so-slow-android-service-restarting-with-start-sticky