8

I want to know if starting up a asynctask from a broadcast receiver considered a bad practice? I basically registered with the C2DM server of google and then when I intercept the onregistered, broadcast receiver, I want to send it to my server.

what is the best way of accomplishing this?

Hades
  • 3,875
  • 3
  • 32
  • 72

2 Answers2

18

Yes, this is considered bad practice. That's because if you start AsyncTask from BroadcastReceiver Android may kill your process if onReceive() returned and there is no other active components running.

The correct way would be to start Service from BroadcastReceiver. And this Service should manage AsyncTask. This way Android will be aware about the active component and Android will not kill it prematurely (unless other critical conditions arise, like not enough memory conditions).

inazaruk
  • 72,103
  • 23
  • 181
  • 156
  • 1
    what if you have a reference to the application context in the async task? could the system still kill the process once the onReceive() returns? – 500865 Sep 12 '12 at 14:20
  • The probability of process being killed is completely irrelevant to who has reference to what inside this process. The probability of being killed is highly dependent on what components are currently active in process, and what stage of their lifecycle they are on. – inazaruk Sep 17 '12 at 08:30
  • 1
    hmm bro, is it possible to elaborate more on the "kill your process if onReceive() returned and there is no other active components running."? is there a doc somewhere? – ericlee Jun 17 '13 at 14:39
2

Starting with Honeycomb, you can call goAsync(), and then you have 10 seconds or so to do your work asynchronously .

Example of usage can be shown here.

Community
  • 1
  • 1
android developer
  • 106,412
  • 122
  • 641
  • 1,128