我已经使用了下面的代码,并按要求显示请求权限的对话。但是当我点击“允许”时,它什么也不做。日志消息不会显示,因为如果权限未被授予,所以我去我的参数来验证位置是“开”,它是“关”。是不是应该开启,因为我授予应用程序访问我的位置? 如果我手动将其打开,然后再次运行应用程序,一旦它请求我的许可,它就会起作用并显示日志消息,但不是要求许可(通过对话)来打开位置当它关闭时)如果用户点击“允许”? 我做错了什么?我要指出,我运行的应用程序上api23无法在android api23上打开位置?
是在我的onCreate代码:
mApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mApiClient.connect();
// 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
,这是我OnConnected方法:
public void onConnected(@Nullable Bundle bundle) {
//start the service
//checking and asking for permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
}
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient, mLocationRequest, this);
} else {
//If everything went fine lets get latitude and longitude
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.v("currentLatitude",currentLatitude + " WORKS " + currentLongitude + "");
}
}
应用程序权限与位置设置完全不同。对于提示用户启用位置模式,请参阅此处:http://stackoverflow.com/a/31816683/4409409 –