我正在尝试构建一个关于Android N中权限请求过程的简单示例。
我在清单文件中声明了ACCESS_COARSE_LOCATION
用法的用法。我试图在自己的方法中处理请求:
public boolean permissionsChecker() {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_REQUEST_PERMISSION_COARSE_LOCATION);
return true;
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
return false;
}
当应用连接时首先询问:
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(permissionsChecker()){
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
}
if(mLastLocation != null){
Log.i(TAG, mLastLocation.getLatitude() + "");
Log.i(TAG, mLastLocation.getLongitude() + "");
} else {
Log.i(TAG, "Still awaiting permissions, something went wrong");
}
}
我的问题是它仍然为mLastLocation
实例返回null并且我能够在调试器中看到它,根据我必须在{}内部有请求代码后设置所有内容的文档{1}}回调,但当我尝试在其中设置mLastLocation实例时,我得到红线告诉我需要发出权限请求:
onRequestPermissionsResult()
如果回调会让我再次要求获得权限,那么请求权限的目的是什么?我究竟做错了什么?我没有从文档中获得太多(我知道缺乏经验),并且想知道如何解决这个问题。任何指针和代码建议将不胜感激!
答案 0 :(得分:1)
permissionChecker()
用法看起来像是在抛弃它。仅仅因为您已经请求了许可并不意味着它已被授予。
此Droicon演讲将帮助解释权限模型和用法:https://youtu.be/WGz-alwVh8A
您可能还会发现此库有助于保持代码更简单,更易于理解:https://github.com/hiqes/andele