0

我正在尝试每秒更新用户位置(我希望每秒显示一条包含用户实际位置的日志消息),为此我必须在运行时询问用户是否允许应用程序获取只能访问他的职位一次(我不得不问,因为 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());
}
4

0 回答 0