I have implemented Push Notification in my appliction. Once the push message is received I call a webservice with the help of AsyncTask. This works fine when the application is being used or is in the memory. But if I stop the application from settings and then if the message is pushed to the device, there is an exception such as "sending message to a Handler on a dead thread". This is probably since the app is not live.
Can someone let me know if its alright to actually remove AsyncTask from push notification receiver and just handle the message?
Regards Sunil
This is due to a bug in AsyncTask in the Android framework. AsyncTask.java has the following code:
It expects this to be initialized on the main thread, but that is not guaranteed since it will be initialized on whichever thread happens to cause the class to run its static initializers. I reproduced this issue where the Handler references a worker thread.
A common pattern that causes this to happen is using the class IntentService. The C2DM sample code does this.
A simple workaround is to add the following code to the application's onCreate method:
This will force AsyncTask to be initialized in the main thread. I filed a bug on this in the android bug database. See http://code.google.com/p/android/issues/detail?id=20915.
IMO AsyncTask should be only used as a helper for background tasks related to Activities (that is, UI).
In your case I would use an IntentService, it is a Service that is prepared to execute background task. So:
In your Activity attach a broadcast receiver for the broadcast in step 4. This way your UI gets notified if it's present, else nothing bad happens. Optionally you can register a default broadcast receiver in your Manifest to handle the broadcast of step 4 and, for example, display a status bar notification.