Update Location data UI using AsyncTaskLoader?

419 views Asked by At

I am using the FusedLocationProvider API for an app. The location of the device should be updating regularly since the user is expected to be moving around all the time, and the app should behave differently depending on the current device location.

In order to keep the Main Thread clear from network requests I wanted to move the code for retrieving location data into a seperate loader. However, I have no clue where to put this part of the code:

locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);


        try{
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
        }catch (SecurityException a){Log.w(TAG,"No location permission.");}

If I put it in the LoaderClass and call this method in loadInBackground(), there will be the error java.lang.NullPointerException: Calling thread must be a prepared Looper thread.

It also feels very wrong to call the Loader again and again. So my question is how can I implement requestLocationUpdates using Loaders so that the Loader updates the changed location which I can retrieve in onLoadFinished() and update the corresponding UI? And what should I do with the method onLocationChanged() of the Location Listener which is needed to be overridden? Or is there perhaps another effective way to move the FusedLocationProvider into a background thread?

It would be really great if someone can help me here, many many thanks!

1

There are 1 answers

5
blackkara On BEST ANSWER

Or is there perhaps another effective way to move the FusedLocationProvider into a background thread? It would be really great if someone can help me here, many many thanks!

If you wanna receive location updates in background thread, you can use Looper version of the requestLocationUpdates method.

requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener, Looper)

In that case, onLocationChanged method will be triggered on the looper's thread.

private HandlerThread mLocThread;
private void initThread(){
    mLocThread = new HandlerThread("locationThread");
    mLocThread.start();
}

private void requestLocUpdates(){
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, 
    locationRequest, this, mLocThread.getLooper());
}

@Override
public void onLocationChanged(Location location) {
    // locationThread thread
}