尝试使用GoogleApiClient获取当前位置不起作用

时间:2017-05-08 17:53:48

标签: android google-api-client

我有一个简单的项目GoogleApiClient来获取经度和纬度,我正在努力使其发挥作用。这就是我到目前为止......

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'

清单:

<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"/>

的活动:

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 + ")");
}

结果日志为空,我不确定可能是什么,也许是权限?谢谢!

1 个答案:

答案 0 :(得分:0)

对于Api Marshmallow及以上给出运行时间许可:

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.
 }
}