4

I've asked a question about keeping service alive but I didn't find the solution so I have another simpler question.

android doc says if android kills a service with START_STICKY on return of onStartCommand in low memory state, it will recreate the service if I'm correct.

but this service gets killed and disappear in running tasks after a period of time but it didn't get recreated! I run this service in android 4.4.2 on my phone, when screen is on, it survived about 20 minutes but when screen is off it disappeared after about 3 or 4 minutes... on my tablet (again android 4.4.2) it stayed longer, about 4 or 5 hours and then got disappeared again (I got different results on different tests). I even test it on android 5 and the result was similar to tablet with android 4.4.2

am I missing something here? I thought service wont get destroyed when we are using return START_STICKY until I call stopService

here's my service:

public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onDestroy() {
        super.onDestroy();
    }
}

sry for bad english :)

2
  • May be related to problem discussed here.
    – Bob Snyder
    Commented Nov 14, 2015 at 16:57
  • which device did u test this?
    – Nicks
    Commented Jul 24, 2016 at 23:32

2 Answers 2

7

May be useful for someone--

This problem has nothing to do with devices with AOSP based ROMs.So android 4.4.2 version is not an issue.

So there are some devices (HUAWEI,LAVA,XIAOMI) are shipped with pre-installed start managers or energy savers, and they run on customized android ROMs. so these devices generally dont entertain a sticky service.

So possible option is to implement something like watchdog timer and check the service in between, if not started, the service can be run again. Possible implications may be on battery consumption though.

1
  • 2
    Thx for such a great tip that was exactly the problem on my Xiaomi redmi note 3 pro running android 5.1!
    – xyman
    Commented May 8, 2017 at 14:13
3

The service does get re-created, not re-started. If you override the onCreate and do a Log.d or a Toast, you will see that onCreate gets called after your activity and app is destroyed.

So the trick to keep it running after it is re-created is to do your code on the onCreate method and use the onStartCommand just to return START_STICKY.

1
  • Xiaomi, Oreo, I can confirm exactly such behavior. Service got recreated, but not restarted. Thanks for unexpected idea! Commented Dec 19, 2018 at 8:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.