Sending message to a Handler on a dead thread when getting a location from an IntentService

你离开我真会死。 提交于 2019-11-27 06:44:42

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"
    >

)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!