I have implemented a simple GPS program that fetches the co-ordinates and displays them on the screen. When I tried to improve on this design and implement an async task, the GP
You can't do that. The thread dies as soon as doInBackground()
returns. The GPS listener is a Handler which requires a Looper
thread to operate. At the beginning of doInBackground()
you need to call Looper.prepare()
then at the end call Looper.loop()
. It will loop forever until you call quit()
on the thread's Looper
object.
AsyncTask
is really designed for one-shot temporary threads though, so I'd use a normal thread for this. Although, there's no reason you couldn't I suppose. You just have to make 100% sure that you end the loop or it will run forever even after the user closes the app.
Java Can't create handler inside thread that has not called Looper.prepare()
like many other things , gps listener can only be listened to by a loopy thread (like the ui thread) . the easiest thing to do would be to it via the ui thread .
also , the gps listener isn't named like this for no reason . only when it gets a location (and that could take time) , it will call the method "onLocationChanged" . you don't need to have asyncTask for this , since all of the calls to "requestLocationUpdates" are asynchronous anyway...
If you want a dirty and not much sensual way:
mLocationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Looper.prepare();
Looper.loop();
if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_MINIMUM_TIME, GPS_MINIMUM_DISTANCE, MyFragment.this);
}
Looper.myLooper().quit();
Basically, it makes the current thread, a main thread on which messages will be executed, after shortly you give up this thread being a main thread. I'm not sure of the consequences of this.