Why so slow Android service restarting with START_STICKY?

浪子不回头ぞ 提交于 2020-01-24 08:50:06

问题


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 your overrided method.
  • If your service class is extended from IntentService class, and if you decide to also override other callback methods, such as onCreate(), onStartCommand(), or onDestroy(), be sure to call the super implementation, so that the IntentService can 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_STICKY will let the service run indefinitely until you explicitly call stopService() or stopSelf(). 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!