最近看过很多android 6.0 以上申请权限的框架,感觉都很麻烦。就自己写了一个,自我感觉还算相对简单的
demo:
String[] permissions = new String[]{ Manifest.permission.RECORD_AUDIO };//权限列表,建议还是单个授权
//初始化授权
PermissionUtil.initPermission(context, permissions)
//检查是否拥有权限,无权限时弹出获取选项对话框
if(PermissionUtil.checkPermission(getContext(), permissions, "录音权限")){
...//执行需要权限的代码
}
initPermission
在Activity 或者你的自定义控件、工具等初始化化时调用checkPermission
checkPermission检查到没有权限时会弹出系统授权对话框。并返回false
如果选择拒绝权限的话,下次将不会弹出该对话框。
isPermission
检查是否拥有权限,返回 boolean
//建议所有需要权限的代码都放在
if(PermissionUtil.checkPermission(getContext(), permissions, "录音权限")){
...//执行需要权限的代码
}
没有权限时提示
工具代码:
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
/**
* 权限
* Created by cheng on 2016/10/19.
*/
public class PermissionUtil {
/**
* 初始化获取权限
*
* @param context
* @param permissions
* @return
*/
public static final boolean initPermission(Context context, @NonNull String[] permissions) {
//版本判断
if (Build.VERSION.SDK_INT >= 23) {
//判断是否拥有权限
boolean isPer = false;
for (int i = 0; i < permissions.length; i++) {
int checkCallPhonePermission1 = context.checkSelfPermission(permissions[i]);
if (checkCallPhonePermission1 != PackageManager.PERMISSION_GRANTED) {
//弹出对话框接收权限
if (context instanceof Activity) {
((Activity) context).requestPermissions(permissions, 60);
}
return false;
}
}
}
return true;
}
/**
* 验证是否有权限
*
* @param context
* @param permissions 权限列表
* @param perName 权限名称
* @return
*/
public static final boolean checkPermission(final Context context, @NonNull String[] permissions, @NonNull String perName) {
//版本判断
if (Build.VERSION.SDK_INT >= 23) {
//判断是否拥有权限
boolean isPer = false;
for (int i = 0; i < permissions.length; i++) {
int checkCallPhonePermission1 = context.checkSelfPermission(permissions[i]);
if (checkCallPhonePermission1 != PackageManager.PERMISSION_GRANTED) {
//弹出对话框接收权限
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
builder.setTitle("缺少" + perName);
builder.setMessage("是否去授予" + perName);
builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package", context.getPackageName(), null));
context.startActivity(intent);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
return false;
}
}
}
return true;
}
}
网友评论
https://github.com/tangpeng/EsayPermissions