Can I start a new stream in BroadcastReceiver?

I need to perform a network operation in BroadcastReceiver .

So far, I have achieved this by creating a new thread:

 @Override public void onReceive(Context context, Intent intent) { new Thread(new Runnable() { public void run() { // network stuff... } }).start(); } 

Is there a risk that the process will be killed before the thread is executed?

Is it better to use an IntentService ? Any other better approach?

+5
source share
2 answers

Is there a risk that the process will be killed before the thread is executed?

If this receiver is registered through the manifest, yes.

If this receiver is registered through registerReceiver() , the lifetime of your process will be determined by other working components.

Is it better to use an IntentService?

If this work lasts a few milliseconds, IMHO, yes, perhaps in agreement with the WakefulBroadcastReceiver .

Any other better approach?

BroadcastReceiver has a goAsync() option that gives you time to work on another thread before starting ANR. I avoid this because it is poorly documented. For example, it does not directly affect your question: what is the significance of the process when this background thread does its job? Does this allow the device to wake up long enough for our work to be completed? And so on. I use IntentService or another form of Service , where I better understand the contract.

+8
source

This is not a good idea. The BroadcastReceiver life cycle lasts until it completes the call to the Receive () function, after which it is destroyed. If you started to start a new stream, the likelihood that the BroadcastReceiver will be killed before the stream ends, which may lead to unexpected behavior.

The best option would be to start a background service, as you said.

+1
source

All Articles