What is the proper way to initiate network communication based on receiving a Broadcast Intent?
Asked Answered
P

1

6

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?

Parasitology answered 30/5, 2012 at 22:21 Comment(0)
P
3

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.

Parasitology answered 6/6, 2012 at 9:10 Comment(2)
AsyncTask is not appropriate here. Basically any asynchronous operation is inappropriate for onReceive(). Take a look at onReceive() documentation for details. Your best bet is to start a Service which initiates the network communication.Rupture
Oh yeah, I'd thought of that before, but I was excited to find out we were on the UI thread, and forgot about that. Thanks.Parasitology

© 2022 - 2024 — McMap. All rights reserved.