Android相机权限检测兼容问题

时间:2021-10-18 15:20:33

转载请注明出处:
http://blog.csdn.net/aa464971/article/details/60587764
Android交流群:146262062

源码
https://github.com/dengyuhan/CameraPermissionCompat

6.0以后出了权限管理,而V4提供了一个权限检测的方法ContextCompat.checkSelfPermission

我在开发过程中遇到一个很诡异的问题:
有部分机型,当相机权限被禁用的时候,checkSelfPermission返回的boolean仍然为true,再打开相机就会报错。

后来换一个思路可以兼容,通过捕捉异常来检测权限

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;

/**
* 摄像头权限检测
* author dengyuhan
* created 2017/3/6 18:08
*/

public class CameraPermissionCompat {

private static final int REQUEST_CODE_CAMERA = 999;
private static OnCameraPermissionListener mOnCameraPermissionListener;


/**
* 检测摄像头权限 没有就会申请
* @param context
* @param listener 申请权限的结果回调
* @return
*/

public static boolean checkCameraPermission(Context context, OnCameraPermissionListener listener) {
mOnCameraPermissionListener = listener;
boolean granted = true;
//魅族或者6.0以下
if (isFlyme() || Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Camera mCamera = null;
try {
mCamera = Camera.open();
// setParameters 是针对魅族MX5 做的。MX5 通过Camera.open() 拿到的Camera
// 对象不为null
Camera.Parameters mParameters = mCamera.getParameters();
mCamera.setParameters(mParameters);
} catch (Exception e) {
granted = false;
}
if (mCamera != null) {
mCamera.release();
}
} else {
granted = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PermissionChecker.PERMISSION_GRANTED;
}
if (granted) {
if (mOnCameraPermissionListener != null) {
mOnCameraPermissionListener.onGrantResult(true);
}
} else {
if (context instanceof Activity) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
}
}
return granted;
}

public static void onRequestPermissionsResult(Context context, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_CAMERA) {
if (mOnCameraPermissionListener != null) {
mOnCameraPermissionListener.onGrantResult(checkCameraPermission(context,null));
}

}
}

private static boolean isFlyme() {
if (Build.BRAND.contains("Meizu")) {
return true;
} else {
return false;
}
}


public interface OnCameraPermissionListener {
void onGrantResult(boolean granted);
}
}