What is the proper way to initiate network communication based on broadcast reception?

I'm getting started with Google C2DM. Part of this process involves receiving broadcasts when registration occurs. In the official C2DM official Google documentation, the sample code shows the following comment in the BrodcastReceiver 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 read, including the documentation for BroadcastReceiver , suggests that starting the stream from onReceive () will almost certainly cause problems, because as soon as onReceive () returns, the process is likely to be killed soon.

Maybe someone just made a mistake and I should just ignore the comment about using a separate thread, but I assume that there is a reason why they said it, even if it is misleading.

Is there a reason why you cannot or should not use a network from the same stream as onReceive () before returning? If this is so problematic, what is the correct way to handle what should be a normal situation, even outside of C2DM? Starting a service?

+6
source share
1 answer

Well, after some research, I found this question , and the selected answer claims that onReceive() works in the user interface thread. It did not occur to me, since this is the declared manifest receiver, as far as I knew, there was not a single user interface thread.

Since you cannot create networks in the Android UI thread, this answers the first part of my question:

  • You both should not and cannot initiate network communication with onReceive() .

The fact that we are in a user interface thread is almost similar to ASyncTask , but the same as manually starting another thread. Thus, it seems that Service is the only option.

+3
source

Source: https://habr.com/ru/post/917058/