I'm getting started with Google's C2DM. Part of this process involves receiving a Broadcast Intent when registration has occurred. In Google's official C2DM documentation, the example code shows the following comment in the BrodcastReceiver's onReceive() method:
// Send the registration ID to the 3rd party site that is sending the messages.
// This should be done in a separate thread.
However, everything I've read, including the documentation for BroadcastReceiver, suggests that starting a thread from onReceive() will almost certainly cause problems, because as soon as onReceive() has returned, the process will likely soon be killed.
It's possible that someone just made a mistake, and that I should just disregard the comment about using a separate thread, but I'm guessing there's a reason they said it, even if it's misleading.
Is there a reason one can't or shouldn't use the network from the same thread as onReceive() before returning? If doing so is problematic, what's the proper way to handle what must be a common situation, even outside of C2DM? Starting a Service?
Creating a BroadcastReceiver The onReceiver() method is first called on the registered Broadcast Receivers when any event occurs. The intent object is passed with all the additional data. A Context object is also available and is used to start an activity or service using context. startActivity(myIntent); or context.
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.
All-to-all communication is a computer communication method in which each sender transmits messages to all receivers within a group. In networking this can be accomplished using broadcast or multicast. This is in contrast with the point-to-point method in which each sender communicates with one receiver.
Okay, after doing some more research, I found this question, and the selected answer states that onReceive()
runs on the UI thread. This hadn't occurred to me -- since this is a Manifest-declared receiver, as far as I knew, there was no UI thread.
Since you can't do networking on the UI thread on Android, that answers the first part of my question:
onReceive()
.The fact that we're on the UI thread makes it almost look like an ASyncTask is appropriate, but that has the same issues as manually starting another thread. So it appears that a Service
is the only option.
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