I have a question related to how Android service behaves when stopped by system. As per my understanding, if system (OS) stops the service due to resources needed, it is responsibility of system to start it again. In this scenario, system would not call onDestroy() when stopping service and onCreate() when starting service, rather it would just call onStartCommand().
If I am creating a thread in onStartCommand(), how would I cleanup thread when system stops service. If I dont stop thread, onStartCommand() would create a new thread.
I think, it may come down to onStartCommand() parameters (intent, flags and startId). They might be different when system starts service after stopping it because it needed resources. Could anyone tell me what would be difference in parameters when service started by startService() command or by system itself (after stopping it)
I can create thread in onCreate() but I am not sure if thread still exists when system stops service. What would be the best way to handle this kind of scenario.
Thanks
That depends upon what you return from
onStartCommand().START_NOT_STICKY, for example, means the OS does not have to start your service again.Whether it calls
onDestroy()would depend a bit on how the service is stopped (e.g., directly or via process termination). However, it should still callonCreate()on the new instance, if and when the OS restarts the service.Ensure that in
onDestroy(), something happens that will cause the thread to go away. EitheronDestroy()will be called (and your service can do its cleanup), or your process is being terminated (and your thread goes away with it).There is a
START_FLAG_REDELIVERYthat will be in the flags passed toonStartCommand(), but AFAIK it will only be set if you returnSTART_REDELIVER_INTENTfromonStartCommand().