描述:适配6.0以下和6.0以上动态权限,并可以解决6.0以上个别手机点拒绝权限后会返回权限允许的回调的问题,例如:OnePlus3T(一加) A3010 7.1.1系统
以拨打电话为例:(注:直接拨打电话需要动态权限判断,唤起拨打电话界面不需要)
一.在build.gradle中添加依赖:
//RxPermissions
compile 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.3@aar'
//RxJava2
implementation "io.reactivex.rxjava2:rxjava:2.0.0"
另外用到了JDK1.8的新特性,也需要在build.gradle中android节点下配置
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
二.工具类
/**
* Created by caoshiyao on 2018/9/6.
* Android6.0权限申请工具类
*/
public class PermissionUtil {
public interface IPermissionListener {
//权限被授权
void permissionGranted();
//权限被拒绝
void permissionDenied();
}
/**
* 申请获取相关权限
*
* @param context
* @param iPermissionListener
* @param toastDetails
* @param permissions
*/
public static void requestPermission(@NonNull Context context, @NonNull IPermissionListener iPermissionListener, @NonNull String toastDetails, @NonNull String... permissions) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
iPermissionListener.permissionGranted();
} else {
new RxPermissions((Activity) context)
.request(permissions)
.subscribe(granted -> {
if (granted) {
if (hasOpsPermission(context, permissions)) {
iPermissionListener.permissionGranted();
} else {
iPermissionListener.permissionDenied();
ToastUtil.showToast(context, toastDetails);
}
} else {
iPermissionListener.permissionDenied();
ToastUtil.showToast(context, toastDetails);
}
});
}
}
/**
* Android6.0权限申请后再判断原生的权限是否真的被授权--适配部分国产机型(小米、华为、vivo、oppo等)
*
* @param context
* @param permissions
* @return
*/
private static boolean hasOpsPermission(@NonNull Context context, @NonNull String... permissions) {
for (String permission : permissions) {
String op = AppOpsManagerCompat.permissionToOp(permission);
int result = AppOpsManagerCompat.noteProxyOp(context, op, context.getPackageName());
if (result == AppOpsManagerCompat.MODE_ALLOWED) return true;
}
return false;
}
}
三.使用方法:
/**
* 检查权限
*/
private void checkPermission() {
PermissionUtil.requestPermission(this, new PermissionUtil.IPermissionListener() {
@Override
public void permissionGranted() {
call();
}
@Override
public void permissionDenied() {
ToastUtil.showToast(PermissionActivity.this,"权限被拒绝");
}
},"权限被拒绝,请设置应用权限",Manifest.permission.CALL_PHONE);
}
/**
* 拨打电话,直接拨打出去
*/
private void call() {
try {
Intent intent = new Intent(Intent.ACTION_CALL);
Uri uri = Uri.parse("tel:" + "10086");
intent.setData(uri);
startActivity(intent);
} catch (SecurityException e) {
e.printStackTrace();
}
}