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

后端 未结 3 586
轻奢々
轻奢々 2020-12-01 01:44

My app needs location fixes on regular basis, even when the phone is not awake. To do this, I am using IntentService with the pattern generously provided by Commonsware. htt

相关标签:
3条回答
  • 2020-12-01 02:04

    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).

    0 讨论(0)
  • 2020-12-01 02:04

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

    )

    0 讨论(0)
  • 2020-12-01 02:11

    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();
    
    0 讨论(0)
提交回复
热议问题