I have a thread that attempts to get the user location.
When the location is received “handler.sendMessage(msg)” is called, and it returns true, but handleMessage is never called.
There are no errors or warnings in logcat.
The code:
public class LocationThread extends Thread implements LocationListener {
// ... Other (non-relevant) methods
@Override
public void run() {
super.run();
Looper.prepare();
mainHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
// This method is never called
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
Looper.loop();
}
@Override
public void onLocationChanged(Location location) {
// SendMessage is executed and returns true
mainHandler.sendMessage(msg);
if (mainHandler != null) {
mainHandler.getLooper().quit();
}
locationManager.removeUpdates(this);
}
}
Most likely this is happening because you are calling
Looper.quit()immediately after posting the message to theHandler. This effectively terminates the message queue operation before theHandlerhas a chance to process it. Sending a message to theHandlersimply posts it to the message queue. The handler will retrieve the message on the next iteration of theLooper. If your goal is to terminate the thread after a location update is received, it would probably be better to callLooper.quit()from insidehandleMessage().Editorial
Furthermore, if the only purpose for standing up this thread is to wait for the location update to come in, it’s unnecessary.
LocationManager.requestLocationUpdates()is an inherently asynchronous process (your main thread isn’t blocked while the location fix is obtained). You can safely have your Activity/Service implementLocationListenerdirectly and receive the location value there.HTH