Issue
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?
Solution
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:
- You both shouldn't and can't initiate network communication from
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.
Answered By - Darshan Rivka Whittle
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.