简体   繁体   中英

Service gets destroyed after unbinding

i have a service that returns START_STICKY onStartCommand, and is started by startService on the Application's onCreate, in my activities i bind to this service interchangeably, but for some reason the Service gets destroyed everytime all my activities unbind to it, but i can gaurantee stopSelf\\stopService was never called. what could be the reason?

Ok, found the answer - DONT relay on a call to startService on Application's onCreate, because in my case i called stopService only when my main activity was exitted by user back press, but even though there were no activities nor services running for my application android did not kill the process and did not release the Application object for garbage collecting, this caused that the next time user launched my app, Application's onCreate was NOT getting called as it already existed, therefore the service's lifetime was handled only by the activites binded to it and this is why it got destroyed when all activites unbounded.

ehhhh Android and their weird design...

The Application.onCreate() only gets called if the application was never run or had been destroyed to free memory. If you need a long lasting Service that continues to run in the background after your Activity has ended, then you can look into running it as a foreground service , which will make Dalvik try not to kill it unless it absolutely has to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM