-1

Good day.

I need to get location everytime the application is launching. The location gathering is happening inside the fragment like so.

I am bulding client like this.

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            // The next two lines tell the new client that “this” current class will handle connection stuff
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            //fourth line adds the LocationServices API endpoint from GooglePlayServices
            .addApi(LocationServices.API)
            .build();

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_LOW_POWER);


@Override
public void onStart() {
    super.onStart();
    if (mSharedHelper.showGreeting()) {
        if (!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
        }
    }
}

   @Override
public void onDestroy() {
    super.onDestroy();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

The onConnected callback is being triggered and I am doing the next.

 @Override
public void onConnected(Bundle bundle) {
    try {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            failedLocate = true;
            hideGreetingCard();
        } else {
            failedLocate = false;
            //If everything went fine lets get latitude and longitude
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();
            YahooWeather yahooWeather = YahooWeather.getInstance();
            yahooWeather.queryYahooWeatherByLatLon(getActivity(), currentLatitude, currentLongitude, this);
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    }

}

The issue is that the location variable is always null no matter what priority i have tried whatever i did nothing works, i got all of the permissions added inside manifest and requested at the runtime accordingly, and besides location variable being null, the onLocationChanged callback is never ever getting triggered but yet you can see that inside onConnected i am requesting the location update but nothing just simply works and no i do not need to use any kind of map to force any kind of simulation to happen i need just simply get the longitude and latitude of the user whenever the app is launched and this fragment is being shown thats much i want. Any ideas?

Volo Apps
  • 235
  • 1
  • 3
  • 12
  • possible duplicate: http://stackoverflow.com/questions/29441384/fusedlocationapi-getlastlocation-always-null – Veneet Reddy Apr 19 '17 at 18:12
  • didn't you read my post? did not you see that i am saying I DO NOT NEED TO INVOKE ANY MAP TO UPDATE LOCATION! – Volo Apps Apr 19 '17 at 18:14
  • that is not fixing the issue i have – Volo Apps Apr 19 '17 at 18:14
  • actually this blog address your issue and how to handle it: http://blog.teamtreehouse.com/beginners-guide-location-android. Look under "Logging the Current Location" – Veneet Reddy Apr 19 '17 at 18:15
  • 1
    "The issue is that the location variable is always null no matter what priority i have tried whatever i did nothing works" -- devices do not continuously monitor for locations. `getLastKnownLocation()` might be used as an optmization, but that's it. "the onLocationChanged callback is never ever getting triggered but yet you can see that inside onConnected i am requesting the location update" -- make sure that you have locations enabled. [Here is a sample app](https://github.com/commonsguy/cw-omnibus/tree/master/Location/FusedNew) that uses the fused location API. – CommonsWare Apr 19 '17 at 18:17
  • i have locations enabled as i am testing on the android 7.0 and request runtime permissions and i have gratned them manually – Volo Apps Apr 19 '17 at 18:19
  • @VeneetReddy tried with that, not working...the callback never gets triggered – Volo Apps Apr 19 '17 at 18:21
  • Check if `mSharedHelper.showGreeting()` is `true` – tahsinRupam Apr 19 '17 at 18:33
  • checked and it is true – Volo Apps Apr 19 '17 at 18:37

2 Answers2

0

Location service is not ready immediately onConnected. Try adding a handler for postdelay action. Get the location 5 seconds after onConnected.

tingyik90
  • 1,641
  • 14
  • 23
0

From the docs of getLastLocation:

Returns the best most recent location currently available.

If a location is not available, which should happen very rarely, null will be returned. The best accuracy available while respecting the location permissions will be returned.

When a last location is not available you need to request one yourself like this:

Declare an instance variable:

private LocationRequest mLocationRequest;

And in onConnected do this (Don't forget to implement LocationListener on your component):

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            // Location is already available
        }
    }

You'll receive the location in onLocationChanged callback:

@Override
public void onLocationChanged(Location location) {
    // Use the location
}

You should call removeLocationUpdates when you need to stop receiving location updates.

if (mGoogleApiClient.isConnected()) {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
}

Since you need the location only once when the app is launched, you can call this in the onLocationChanged callback.

Veneet Reddy
  • 2,707
  • 1
  • 24
  • 40
  • ok i will try this but before that i have 1 question, i do not need any precious longitude and latitude so the simplies network provide will be fully perfect as i need precious around the CITY and not street or meteres, so the hugest even drift will not give an issue, basically i am saying that i have seen that you are using HIGH_ACCURACY , so can i use the POWER_LOW mode isntead of HIGH_ACCURACY and it will work same way? as the high accuracy will require GPS and i do not want any GPS to be invoked as the network is fairly enough – Volo Apps Apr 19 '17 at 18:44
  • Yeah it should work the same way, but with lesser accuracy. – Veneet Reddy Apr 19 '17 at 18:49
  • perfect, testing it now – Volo Apps Apr 19 '17 at 18:53
  • damn this not working....neither with high accuracy nor with no power the damned onLocationChanged callback is simply not getting triggered i dont know what the hell is wrong wiht this – Volo Apps Apr 19 '17 at 18:58