russjr08 russjr08 - 4 months ago 21
Android Question

Keeping a TileService active?

I have a Tile that, when active, runs a timer, performs a task for those five minutes, and then goes back to it's inactive state after a certain amount of time.

The problem I'm running into however is the service getting killed. I'm already calling

startForeground(id)
when said timer starts, but my service still gets killed nonetheless. I'm also returning
START_STICKY
from
onStartCommand(intent, flags, startID)
.

Is there anyway to absolutely prevent it from being killed, or am I just out of luck here?

Answer

I managed to solve this by using @CommonWare's advice. I abstracted all of my logic to a regular Service class, and am calling startService() from my Tile's service class.

The one road bump I ran into was figuring out how to get the Tile instance to the new Service (which handles updating the tile's text and state), but solved this by using an Application class to hold a reference to the Tile. (TileService updates this reference every onClick, before calling startService())

It's probably not the cleanest and best way to do it, but it's the way that I'm choosing to roll with for now.

Comments