I need to perform a network operation in a BroadcastReceiver
.
So far I achieve it by starting a new thread:
@Override
public void onReceive(Context context, Intent intent) {
new Thread(new Runnable() {
public void run() {
// network stuff...
}
}).start();
}
Is there any risk that the process will be killed before the thread is done?
Is it better to use an IntentService
instead? Any other better approach?
Does BroadcastReceiver. onReceive always run in the UI thread? Yes.
A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent) . Once your code returns from this function, the system considers the object to be finished and no longer active.
Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.
Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.
Is there any risk that the process will be killed before the thread is done?
If this receiver is registered via the manifest, yes.
If this receiver is registered via registerReceiver()
, the lifetime of your process will be determined by other running components.
Is it better to use an IntentService instead?
If that work will be over a few milliseconds, IMHO, yes, probably in concert with WakefulBroadcastReceiver
.
Any other better approach?
There is a goAsync()
option on BroadcastReceiver
that gives you a window of time to do work in another thread before triggering an ANR. I avoid this, because it is poorly documented. For example, it does not directly address your question: what is the process importance while this background thread is doing its work? Does this keep the device awake long enough for our work to get done? And so on. I'll use an IntentService
or some other form of Service
, where I have better understanding of the contract.
It isn't the best idea. The life-cycle of a BroadcastReceiver lasts as long as it takes to finish calling onReceive(), after that it's destroyed. If you were to start running a new thread, there's a chance the BroadcastReceiver would be killed before the thread completes, which would wind up in some unexpected behaviour.
The better option would be to start a background service, like you said.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With