Android相機許可權檢測相容問題
阿新 • • 發佈:2019-01-10
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);
}
}