Search code examples
androidbroadcastreceiveralarmmanagerandroid-alarms

Doubts with BroadcastReceiver


I have an alarm that obviously calls a receiver and in the receiver it have to do some tasks and it may take some time to be done. But i heard that the onReceive() method is killed after some seconds. I made a debug on my code and "stopped" inside the receiver and suddenly the debug stops, it happens because the onReceive() was killed? So, what should i do?


Solution

  • But i heard that the onReceive() method is killed after some seconds

    Correct. onReceive() is called on the main application thread. You want to get off of that thread as soon as possible. If your UI happens to be in the foreground when the broadcast is received, your UI will be frozen. Even if your UI is not in the foreground, you cannot take very long on that thread without your work being terminated.

    So, what should i do?

    Delegate the work to an IntentService, where you start that service in onReceive(). If the work may take 15+ seconds, I would recommend using WakefulBroadcastReceiver, so that you can ensure the device will stay awake long enough for your work to complete. But even then, "some time to be done" should be measured in seconds, maybe minutes.