Search code examples
androidgoogle-api-client

Trying to get current location using GoogleApiClient is not Working


I have a simple project with GoogleApiClient to get a Latitude and Longitude and I'm struggling to make it work. This is what I have so far...

Gradle :

compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-plus:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'

Manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />   
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Activity:

public class MainActivity extends AppCompatActivity
    implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener....

private GoogleApiClient mGoogleApiClient;...

private synchronized void callConnection() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i("LOG", "onConnected(" + bundle +  ")");
    try{
        Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(l != null){
            Log.i("LOG","latitude: " + l.getLatitude());
            Log.i("LOG","longitude: " + l.getLongitude());
        }
    }catch (SecurityException ex){
        Toast.makeText(this, ex.toString(), Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.i("LOG","onConnectionSuspended(" + i + ")");

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i("LOG","onConnectionSuspended(" + connectionResult + ")");
}

And the Result Log is null, I'm not sure what could be, maybe the Permission ?Thanks!


Solution

  • For Api Marshmallow and above give run time permission as:

    if (ContextCompat.checkSelfPermission(this, 
    Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
       // do your work
    } else {
    //  request permission.
                ActivityCompat.requestPermissions(this, new String[]
    {
    Manifest.permission.ACCESS_FINE_LOCATION}, MY_LOCATION_REQUEST_CODE);
    }
    
    public void onRequestPermissionsResult(int requestCode, String[] 
    permissions, int[] grantResults) {
    if (requestCode == MY_LOCATION_REQUEST_CODE) {
      if (permissions.length == 1 &&
          permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
          grantResults[0] == PackageManager.PERMISSION_GRANTED) {
     /// granted do your work
     } else {
      // Permission was denied. Display an error message.
     }
    }