-3

I'm first checking if Location is ON using Android LocationServices.SettingsApi, if it's not I present standard location setting dialog using Android documentation example. Later if user enables the Location I use LocationServices.FusedLocationApi.getLastLocation() to get current location. Here as below:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ENABLE_LOCATION_REQUEST_CODE) {
        switch (resultCode) {
            case Activity.RESULT_OK:
                Location location = LocationServices.FusedLocationApi
                                       .getLastLocation(mGoogleApiClient);
                while (location == null) {
                    location = LocationServices.FusedLocationApi
                        .getLastLocation(mGoogleApiClient);
                }
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(this, "Location not enabled!", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }
}

LocationServices.FusedLocationApi .getLastLocation() takes around 1 second in my device to return non null value after enabling Location. The problem is that I'm using while statement till LocationServices.FusedLocationApi .getLastLocation() returns non null value. I think the way I'm doing this in UI Thread is not right. Maybe I can do it in background thread but what I want to know is there some better native way of doing.

Mohd Ali
  • 311
  • 2
  • 13

2 Answers2

0

you could find the answer in this link :: already solved

LocationClient getLastLocation() return null

Community
  • 1
  • 1
msmukesh4
  • 589
  • 4
  • 7
  • what are you saying "fused location wont work on pre-lollipop"...really :).. please check and its not a answer... – Bharatesh Mar 03 '16 at 12:54
0

Instead of using background thread you can use Handler.postDelayed()

if(location==null){
    new android.os.Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
    }, 2000);//your waiting time.. I prefer 2 secs
}
Bharatesh
  • 8,943
  • 3
  • 38
  • 67