您的位置:首页 > 移动开发 > Android开发

Android 6.0开发的权限注意事项

2016-07-26 10:42 549 查看
由于Android 6.0推出了新的权限机制,对于敏感权限进行了限制,即使在Android的AndroidManifest.xml中申明仍然需要进行授权,所以代码解决方法如下:

节选自Dropbox的Demo

private void performWithPermissions(final FileAction action) {
if (hasPermissionsForAction(action)) {
performAction(action);
return;
}

if (shouldDisplayRationaleForAction(action)) {
new AlertDialog.Builder(this)
.setMessage("This app requires storage access to download and upload files.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissionsForAction(action);
}
})
.setNegativeButton("Cancel", null)
.create()
.show();
} else {
requestPermissionsForAction(action);
}
}

private boolean hasPermissionsForAction(FileAction action) {
for (String permission : action.getPermissions()) {
int result = ContextCompat.checkSelfPermission(this, permission);
if (result == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}

private boolean shouldDisplayRationaleForAction(FileAction action) {
for (String permission : action.getPermissions()) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
return true;
}
}
return false;
}

private void requestPermissionsForAction(FileAction action) {
ActivityCompat.requestPermissions(
this,
action.getPermissions(),
action.getCode()
);
}

private enum FileAction {
DOWNLOAD(Manifest.permission.WRITE_EXTERNAL_STORAGE),
UPLOAD(Manifest.permission.READ_EXTERNAL_STORAGE);

private static final FileAction [] values = values();

private final String [] permissions;

FileAction(String ... permissions) {
this.permissions = permissions;
}

public int getCode() {
return ordinal();
}

public String [] getPermissions() {
return permissions;
}

public static FileAction fromCode(int code) {
if (code < 0 || code >= values.length) {
throw new IllegalArgumentException("Invalid FileAction code: " + code);
}
return values[code];
}
}

要不然引导用户在App Setting中授权:



最后是效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: