javaandroidasynchronousandroid-fusedlocation

How to wait for requestLocationUpdates() callback intent to finish?


I want to wait for the callback intent in FusedLocationProviderClient.requestLocationUpdates() to finish. Is a while loop with a timeout the best solution? Below is an example, sans timeout.

Normally I would use startWakefulService() to wait for an asynchronous service to complete, but I don't know a way to use it with requestLocationUpdates().

Task t = flpc.requestLocationUpdates(locationRequest, pe);
while (! t.isSuccessful()) {
    Log.v(TAG, "Waiting for result...");
}

Solution

  • If you're familiar with RxJava/RxAndroid a bit you can wrap your method call in an Observable for example (or Callable, Single, whatever you see best), run it on another thread than the UI and then once you have a result from your method you receive it on the main thread, and do whatever you want with it.

    In code it will look like this:

    Observable.fromCallable(() -> flpc.requestLocationUpdates(locationRequest, pe))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(task -> onLocationUpdatesSuccess(task), throwable -> Log.e(TAG, throwable.getMessage()));
    

    Otherwise another solution would be to wrap your method in an AsyncTask for example, you'd end up with something like this:

        new AsyncTask<Void, Void, Task>() {
                @Override
                protected Task doInBackground(Void... params) {
                    return flpc.requestLocationUpdates(locationRequest, pe);
                }
    
                @Override
                protected void onPostExecute(Task task) {
                    onLocationUpdatesSuccess(task)
                }
        }.execute();