我正在尝试添加运行时权限android(6.0.1)API 23,如果我使用SDK版本( min和目标版本都是23 ),它会很好,如下所示,
<uses-sdk
android:minSdkVersion="23"
android:targetSdkVersion="23" />
如果我更改android:minSdkVersion(少于23)
例如:
我收到以下错误:
呼叫需要API级别23(当前最小值为14): android.app.Activity#requestPermissions,checkSelfPermission
对于以下2种方法,
1)requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS)
2)checkSelfPermission(permission)
我尝试了ActivityCompat.checkSelfPermission()
,ContextCompat.checkSelfPermission()
两者都无效。
我遗失的东西无法理解......
答案 0 :(得分:32)
检查权限:
ContextCompat.checkSelfPermission(Context context, String permission)
请求权限:
ActivityCompat.requestPermissions(Activity activity, String[] permissions, int requestCode)
或在support-v4 Fragment
requestPermissions(String[] permissions, int requestCode)
答案 1 :(得分:30)
检查目标&gt; = 23或只是在方法
上方添加以下行@TargetApi(Build.VERSION_CODES.M)
例如,如果要检查存储权限,则可以参考此功能
@TargetApi(Build.VERSION_CODES.M)
public boolean CheckStoragePermission() {
int permissionCheckRead = ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheckRead != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an expanation 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.
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
Define.PERMISSION_STORAGE);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
Define.PERMISSION_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
return false;
} else
return true;
}
答案 2 :(得分:13)
试试这种方式
if (Build.VERSION.SDK_INT < 23) {
// your code
} else {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
requestContactsPermissions1();
} else {
// your code
}
}
编辑:
在较低级别(您的应用)build.gradle
添加依赖项块:
compile 'com.android.support:appcompat-v7:23.1.1'
或仅在您需要设计支持库
时添加以下内容compile 'com.android.support:design:23.1.1'
使用以上
之一答案 3 :(得分:3)
这是因为 API 23 中添加了checkSelfPermission()
。所以你必须有条件地编码:
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
//use checkSelfPermission()
} else {
//simply use the required feature
//as the user has already granted permission to them during installation
}
答案 4 :(得分:0)
在调用请求权限
之前检查设备sdk if(Build.VERSION.SDK_INT==Build.VERSION_CODES.M)
{
//call the request permission here
}