简体   繁体   中英

How to send broadcast when Android service goes down?

I would like to issue broadcast when service goes down. What callback is guaranteed to run when this happens? I want other apps to know its down, I cannot take a chance that it goes down and no one knows about it. So at point in the service lifecycle (which method) should I issue the sendBroadcast(ImGoingDown)? For example, how soon would onDestroy() be called?

While most answers here are aiding in the onDestroy approach, there are many events on your service being destroyed that you cannot intervene. For instance, if the user has force closed your application, your service is destroyed, but onDestroy will NOT be executed.

On a common scenario, your service would be destroyed when it has ran out of operations (mostly know as finished), when no other process that are bound to the service, or when its stopSelf() is executed, and most common, when the device is running low on RAM.

onDestroy would be the scenario where you can restart it.

As a suggestion, if the device has killed your process due to low RAM, dont restart it right away. set a Handler or AlarmManager to start it a bit later (so the lack of memmomry dont execute in back again.)

You can fire the broadcast in onDestroy(). This is the last call the service receives before getting destroyed. Service lifecycle ends with this call.

If you are running a background service that means you must be doing something in background, sending broadcast from onDestroy() might not be a best practice .

Think, your service gets destroyed because the task you wanted to run is completed, then you might don't want to send a broadcast in that case. You want to send a broadcast only when the service is killed right? So the better approach is to setting a boolean , say isTaskFinised, and if it returns false only then your onDestroy() should send a broadcast.

@Override
public void onDestroy(){
    if(!isTaskFinished){
        //send a broadcast
    }
}

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