Sending Message to a Handler on a Dead Thread When Getting a Location from an Intentservice

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

sending message to a handler on a dead thread

IntentServices create a new thread when you call the onHandleIntent method, and then kills that thread as soon as that onHandleIntent method returns.

You need to create your listener somewhere else, IntentServices aren't safe for setting up listeners because they die. They're mainly used for executing a short task outside of the main thread. See a similar question here.

Edit: Also see documentation on IntentService.

Message to a handler in dead thread

There are several things to consider here that can help you get rid of your errors and get a cleaner code:

  • The alarm should be scheduled using the AlarmManager
  • The ServiceGps could be launched by a WakefulBroadcastReceiver, so you don't have to handle wake lock yourself.
  • If the target is below 19, you could benefit from using setRepeating... method in the AlarmManager.

** Don't forget the permissions in your Manifest.

Hope it helps.

java.lang.RuntimeException: Handler (android.os.Handler) sending message to a Handler on a dead thread

The problem here is that you are creating a Toast inside a thread that is managed by the IntentService. The system will use the Handler associated with this thread to show and hide the Toast.

First the Toast will be shown correctly, but when the system tries to hide it, after the onHandleIntent method has finished, the error "sending message to a Handler on a dead thread" will be thrown because the thread on which the Toast was created is no longer valid, and the Toast will not disappear.

To avoid this you should show the Toast posting a message to the Main Thread. Here's an example:

    // create a handler to post messages to the main thread
Handler mHandler = new Handler(getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
});


Related Topics



Leave a reply



Submit