如何在Android 6中添加多个权限并在模拟器中进行测试?
作者:互联网
我正在制作一个允许自动添加Android 6.0和Android M权限的应用程序.我的权限包括
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
我使用以下代码为Android 6.0版本添加了权限
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkAndRequestPermissions()) {
Log.d ("TAG", "Permissions are granted");
}
}
private boolean checkAndRequestPermissions() {
if (Build.VERSION.SDK_INT >= 23) {
int permissionSTORAGE = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionRECORDAUDIO = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionSTORAGE != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionRECORDAUDIO != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.RECORD_AUDIO);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
else
return true;
}}
我在上面的代码中有两个问题.
>是否可以在模拟器(Android M,SDK 24)中检查权限?
>我的实现正确吗?我没有真实的设备,因此无法确认上述代码.
解决方法:
请正确阅读我的代码并根据需要进行修改
只要在ActivityCompat.requestPermissions(…)调用中包含所有4个权限,Android就会像您提到的那样自动将它们分页.
我有一个帮助程序方法来检查多个权限,看看是否其中任何一个都不被授予.
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
然后只需发送所有权限即可. Android只会询问需要的东西.
String[] PERMISSIONS = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if(!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
标签:android-permissions,android-6-0-marshmallow,android-audiorecord,android 来源: https://codeday.me/bug/20191118/2026851.html