动态申请权限
提示:Android 6.0也就是API等级23之后,获取权限需要动态申请,否则程序无法正常使用。
前言
提示Android6.0动态申请权限
提示:以下是本篇文章正文内容,下面案例可供参考
一、静态申请?
示例:
<!-- 相机权限 -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- 录音权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- 读写权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
二、使用步骤
代码如下(示例):
fun readWritePermissions() {
val PERMISSION_M = arrayOf(
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val mPermissionList =
ArrayList<String>()
for (i in PERMISSION_M.indices) {
if (ContextCompat.checkSelfPermission(
this,
PERMISSION_M.get(i)
)
!= PackageManager.PERMISSION_GRANTED
) {
mPermissionList.add(PERMISSION_M.get(i))
}
}
if (mPermissionList.isEmpty()) {
} else {
val permissionsNew =
mPermissionList.toTypedArray()
ActivityCompat.requestPermissions(
this,
permissionsNew,
0
)
}
}
}
private static String[] PERMISSION_M = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public void addPermissByPermissionList(Activity activity) {
//Android 6.0开始的动态权限,这里进行版本判断
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ArrayList<String> mPermissionList = new ArrayList<>();
for (int i = 0; i < PERMISSION_M.length; i++) {
if (ContextCompat.checkSelfPermission(activity, PERMISSION_M[i])
!= PackageManager.PERMISSION_GRANTED) {
mPermissionList.add(PERMISSION_M[i]);
}
}
if (mPermissionList.isEmpty()) {
} else {
//请求权限方法
String[] permissionsNew = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
ActivityCompat.requestPermissions(activity, permissionsNew, 0); //这个触发下面onRequestPermissionsResult这个回调
}
}
}
|