I've got a service that instantiates a web server using com.koushikdutta.async.AsyncHttpServer. Inside a callback, I need to instantiate a class which is calling requestLocationUpdates on LocationManager. But this is causing an exception:
Can't create handler inside thread that has not called Looper.prepare()
I'm trying to setup a looper/handler to get rid of this error, but I'm not exactly sure how to proceed. This example shows how to create a thread class which creates a handler, but not how to use it. In this answer which mistakenly claims you can't use a Handler but then provides a link to showing how to do that is some code which I have adapted to look like this:
Handler handler = new Handler();
final GPSListener gps;
handler.post(new Runnable() {
@Override
public void run() {
gps = new GPSListener(ctx,ews);
}
})
This code is in the callback in response to an HTTP request. But there is an immediate problem. I can't use the gps
variable in the Runnable unless it is declared final. But if I declare it final outside the Runnable, then it tells me that I can't initialize it since it's final. But I can't initialize it outside the Runnable, because the whole point of putting it in the Runnable is to avoid the exception caused by trying to the constructor trying to call requestLocationUpdates instead a thread which has not called Looper.prepare(). Additionally, this gps
variable also needs to be outside the Runnable because another callback (on connection close) needs to call another function on it to shut things down. Further, the variable has to be local to the callback, because it needs to separately instantiate a new object each time the callback is called.
I'm not sure the way I'm trying to set up the handler is even correct, and assuming it is, how can I get past the above issues?