Sending message to a Handler on a dead thread when getting a location from an IntentService
You cannot safely register listeners from an IntentService
, as the IntentService
goes away as soon as onHandleIntent()
(a.k.a., doWakefulWork()
) completes. Instead, you will need to use a regular service, plus handle details like timeouts (e.g., the user is in a basement and cannot get a GPS signal).
I've had a similar situation, and I've used the android Looper facility to good effect: http://developer.android.com/reference/android/os/Looper.html
concretely, just after calling the function setting up the the listener, I call:
Looper.loop();
That blocks the current thread so it doesn't die but at the same time lets it process events, so you'll have a chance to get notified when your listener is called. A simple loop would prevent you from getting notified when the listener is called.
And when the listener is called and I'm done processing its data, I put:
Looper.myLooper().quit();
For others like me: I had a similar problem related to AsyncTask
. As I understand, that class assumes that it is initialized on the UI (main) thread.
A workaround (one of several possible) is to place the following in MyApplication
class:
@Override
public void onCreate() {
// workaround for http://code.google.com/p/android/issues/detail?id=20915
try {
Class.forName("android.os.AsyncTask");
} catch (ClassNotFoundException e) {}
super.onCreate();
}
(do not forget to mention it in AndroidManifest.xml
:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name="MyApplication"
>
)