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?
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.