如何在运行时请求权限时正确更新位置?

时间:2017-08-14 13:02:40

标签: android google-location-services

我正在尝试每秒更新用户位置(每秒我想要显示包含用户实际位置的日志消息),为此我必须在运行时询问用户是否要允许app只能访问他的位置一次(我不得不问,因为API 24需要这个)。用户接受后,应用程序不再询问。

但是onLocationChanged没有被调用。

@Override
protected void onCreate(Bundle bundle) {
    //initializing UI
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
    mLocationRequest.setInterval(1000);

    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            return;
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if(requestCode == 1) {
        if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults.length > 0) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.i("LOCATION", location.toString());
}

0 个答案:

没有答案
相关问题