android动态获取权限——公共方法,拿过来传参直接用

android动态获取权限——公共方法,拿过来传参直接用话不多说 首先列举一下需要动态获取的权限 publicclassP publicstatic GROUP Manifest permission group CAL

大家好,欢迎来到IT知识分享网。

话不多说,首先列举一下需要动态获取的权限

public class PermissionModel { public static String CALENDAR_GROUP = Manifest.permission_group.CALENDAR; public static String READ_CALENDAR = Manifest.permission.READ_CALENDAR; public static String WRITE_CALENDAR = Manifest.permission.WRITE_CALENDAR; public static String CAMERA_GROUP = Manifest.permission_group.CAMERA; public static String CAMERA = Manifest.permission.CAMERA; public static String CONTACTS_GROUP = Manifest.permission_group.CONTACTS; public static String READ_CONTACTS = Manifest.permission.READ_CONTACTS; public static String WRITE_CONTACTS = Manifest.permission.WRITE_CONTACTS; public static String GET_ACCOUNTS = Manifest.permission.GET_ACCOUNTS; public static String LOCATION_GROUP = Manifest.permission_group.LOCATION; public static String ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION; public static String ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION; public static String MICROPHONE_GROUP = Manifest.permission_group.MICROPHONE; public static String RECORD_AUDIO = Manifest.permission.RECORD_AUDIO; public static String PHONE_GROUP = Manifest.permission_group.PHONE; public static String READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE; public static String CALL_PHONE = Manifest.permission.CALL_PHONE; public static String READ_CALL_LOG = Manifest.permission.READ_CALL_LOG; public static String WRITE_CALL_LOG = Manifest.permission.WRITE_CALL_LOG; public static String ADD_VOICEMAIL = Manifest.permission.ADD_VOICEMAIL; public static String USE_SIP = Manifest.permission.USE_SIP; public static String PROCESS_OUTGOING_CALLS = Manifest.permission.PROCESS_OUTGOING_CALLS; public static String SENSORS_GROUP = Manifest.permission_group.SENSORS; public static String BODY_SENSORS = Manifest.permission.BODY_SENSORS; public static String SMS_GROUP = Manifest.permission_group.SMS; public static String SEND_SMS = Manifest.permission.SEND_SMS; public static String READ_SMS = Manifest.permission.READ_SMS; public static String RECEIVE_SMS = Manifest.permission.RECEIVE_SMS; public static String RECEIVE_WAP_PUSH = Manifest.permission.RECEIVE_WAP_PUSH; public static String RECEIVE_MMS = Manifest.permission.RECEIVE_MMS; public static String STORAGE_GROUP = Manifest.permission_group.STORAGE; public static String READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE; public static String WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE; }

再来一个检查权限的小小工具类

public class PermissionUtil { public static boolean verifyPermissions(int[] grantResults) { // Verify that each required permission has been granted, otherwise return false. for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public static boolean checkSelfPermissions(Context context, String[] permissionName){ for (String permission : permissionName) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } / *判断 权限是否在AndroidManifest.xml声请 */ public static boolean permissionExists(Context context, @NonNull String permissionName) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); if (packageInfo.requestedPermissions != null) { for (String p : packageInfo.requestedPermissions) { if (p.equals(permissionName)) { return true; } } } } catch (Exception e) { e.printStackTrace(); } return false; } / * 得到所有没有获得权限 */ public static String[] getDeniedPermissons(Context context, String[] permissionName){ ArrayList<String> needPermissons = new ArrayList<>(); for (String permission: permissionName){ if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { needPermissons.add(permission); } } return needPermissons.toArray(new String[needPermissons.size()]); } }

再来个回调,用来处理权限被允许或者被拒之后的逻辑

public interface PermissionCallback { / * 权限被允许 */ void onPermissionGranted(); / * 权限被拒绝——与onPermissionRejectNoPrompts()实现一个就行 * forceAccepting == true 时,用onPermissionRejectNoPrompts() * forceAccepting == false 时,用onPermissionReject() */ void onPermissionReject(); }

由于在权限被拒的时候 有个小框框,<点击【拒绝】后不再提示>,所以又单独写了一个回调用来处理这种情况下的权限被拒绝。

public interface PermissionDetailCallback extends PermissionCallback { / * 被拒且不再提示的权限——用onPermissionReject()实现一个就行 * forceAccepting == true 时,用onPermissionRejectNoPrompts() * forceAccepting == false 时,用onPermissionReject() */ void onPermissionRejectNoPrompts(String[] permissions); }

前面都是准备工作,下面最正经的部分来了(虽然之前也挺正经的)

public class PermissionHelper { private Context appContext; private WrapperModel model = null; public static PermissionHelper permissionHelper = null; private int requestPermissionsLenth = 0; //表示已经接收到的权限的数量 如果接口是PermissionDetailCallback 权限由两部分组成 public static PermissionHelper getInstance() { if (permissionHelper == null) { permissionHelper = new PermissionHelper(); } return permissionHelper; } private PermissionHelper() { } public PermissionHelper with(Activity activity) { model = new WrapperModel(activity); return this; } public PermissionHelper with(android.app.Fragment fragment) { model = new WrapperModel(fragment); return this; } public PermissionHelper with(Fragment fragment) { model = new WrapperModel(fragment); return this; } public PermissionHelper setPermissions(String... permissions) { if (model == null) { throw new IllegalArgumentException("you must call wth() mothed first"); } model.permissions = permissions; return this; } public PermissionHelper setRequestCode(int requestCode) { if (model == null) { throw new IllegalArgumentException("you must call wth() mothed first"); } model.requestCode = requestCode; return this; } public PermissionHelper setForceAccepting(boolean forceAccepting) { if (model == null) { throw new IllegalArgumentException("you must call wth() mothed first"); } model.forceAccepting = forceAccepting; return this; } public PermissionHelper setPermissonCallback(PermissionCallback callback) { if (model == null) { throw new IllegalArgumentException("you must call wth() mothed first"); } model.permissionCallback = callback; return this; } public void requestPermissions() { checkWrapperModel(model); requestPermissionsModel(model); } private void requestPermissionsModel(WrapperModel pModel) { if (appContext == null) { appContext = getContext(pModel.container).getApplicationContext(); } for (String permission : pModel.permissions) { if (!PermissionUtil.permissionExists(appContext, permission)) { throw new IllegalArgumentException(permission + " must be define on the AndroidManifest.xml"); } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { pModel.permissions = PermissionUtil.getDeniedPermissons(appContext, pModel.permissions); if (pModel.permissions == null || pModel.permissions.length == 0) { pModel.permissionCallback.onPermissionGranted(); afterPermissonCall(); } else { requestPermissions(pModel.container, pModel.permissions, pModel.requestCode); } } else { if (PermissionUtil.checkSelfPermissions(appContext, pModel.permissions)) { pModel.permissionCallback.onPermissionGranted(); } else { pModel.permissionCallback.onPermissionReject(); } afterPermissonCall(); } } private void afterPermissonCall() { model = null; appContext = null; requestPermissionsLenth = 0; LogUtils.d("权限回调完成"); } / * 只为实现了 PermissionDetailCallback 调用 * * @param permission */ public void requestAfterExplanation(String[] permission) { if (permission.length != 0) { //表示每一个都需要解释 requestPermissions(model.container, permission, model.requestCode); } } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { LogUtils.d("请求权限" + "回调的requestCode=" + requestCode + " 而请求的requestCode = " + model.requestCode); if (requestCode == model.requestCode) { String[] deniedPermissons = PermissionUtil.getDeniedPermissons(appContext, model.permissions); if (PermissionUtil.getDeniedPermissons(appContext, model.permissions).length == 0) { model.permissionCallback.onPermissionGranted(); afterPermissonCall(); } else { requestPermissionsLenth += permissions.length; if (requestPermissionsLenth == model.permissions.length) { model.permissionCallback.onPermissionReject(); if (model.forceAccepting) { // 再次声请权限 model.permissions = deniedPermissons; requestPermissionsLenth = 0; if (model.permissionCallback instanceof PermissionDetailCallback) { //add by navy List<String> noExplainPermissions = new ArrayList<>(); List<String> explainPermissions = new ArrayList<>(); for (String permission : model.permissions) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(model.container), permission)) { explainPermissions.add(permission); } else { noExplainPermissions.add(permission); } } if (explainPermissions.size() != 0) { requestPermissions(model.container, model.permissions, model.requestCode); } if (noExplainPermissions.size() != 0) { ((PermissionDetailCallback) model.permissionCallback).onPermissionRejectNoPrompts(explainPermissions.toArray(new String[]{})); } } else { requestPermissions(model.container, model.permissions, model.requestCode); } } else { afterPermissonCall(); } } } } else { LogUtils.e("发生未知错误" + "回调的requestCode=" + requestCode + " 而请求的requestCode = model.requestCode"); } } public static void checkWrapperModel(WrapperModel wrapperModel) { if (wrapperModel == null) { throw new NullPointerException("WrapperModel cannot be null"); } if (wrapperModel.container == null) { throw new NullPointerException("WrapperModel container cannot be null"); } if (!(wrapperModel.container instanceof Activity || wrapperModel.container instanceof android.app.Fragment || wrapperModel.container instanceof Fragment)) { throw new IllegalArgumentException("WrapperModel container must be Activity ,or Fragment"); } if (wrapperModel.requestCode <= 0) { throw new IllegalArgumentException("RequestCode must >0"); } if (wrapperModel.permissions == null || wrapperModel.permissions.length == 0) { throw new IllegalArgumentException("permissions cannot be null, or it's lenth must >0"); } if (wrapperModel.permissionCallback == null) { throw new NullPointerException("permissionCallback cannot be null"); } } private Context getContext(Object container) { if (container instanceof Activity) { return (Activity) container; } else if (container instanceof Fragment) { return ((Fragment) container).getContext(); } else { throw new IllegalArgumentException("container must be Activity ,or Fragment"); } } private Activity getActivity(Object container) { if (container instanceof Activity) { return (Activity) container; } else if (container instanceof Fragment) { return ((Fragment) container).getActivity(); } else if (container instanceof android.app.Fragment) { return ((android.app.Fragment) container).getActivity(); } else { throw new IllegalArgumentException("container must be Activity ,or Fragment"); } } @TargetApi(value = Build.VERSION_CODES.M) private synchronized void requestPermissions(Object container, @NonNull String[] permissions, int requestCode) { if (container instanceof Activity) { ActivityCompat.requestPermissions(((Activity) container), permissions, requestCode); } else if (container instanceof Fragment) { ((Fragment) container).requestPermissions(permissions, requestCode); } else if (container instanceof android.app.Fragment) { ((android.app.Fragment) container).requestPermissions(permissions, requestCode); } else { throw new IllegalArgumentException("container must be Activity ,or Fragment"); } } public static class WrapperModel { private Object container;//可以是Activity,也可以是Fragment private String[] permissions; private PermissionCallback permissionCallback; private int requestCode = 8080; private boolean forceAccepting = false;//是否强制授权 public WrapperModel(Object container) { this.container = container; } @Override public String toString() { return "WrapperModel{" + "container=" + container + ", permissions=" + Arrays.toString(permissions) + ", permissionCallback=" + permissionCallback + ", requestCode=" + requestCode + '}'; } } }

所有的都准备完毕,在想请求权限的时候,比如页面初始化,或者点击事件等等,直接拿来用,例如:

/ * 请求所有权限 */ private void requestPermissions() { PermissionHelper.getInstance().with(this) .setPermissions(PermissionModel.READ_PHONE_STATE, PermissionModel.CAMERA, PermissionModel.ACCESS_FINE_LOCATION, PermissionModel.ACCESS_COARSE_LOCATION, PermissionModel.READ_EXTERNAL_STORAGE, PermissionModel.WRITE_EXTERNAL_STORAGE)//这块请求了四个权限,电话+相机+定位+存储,后面两组的权限不唯一,我都列举出来了,各写一个也可 .setRequestCode("4001") .setForceAccepting(false) //表示必须强制用户接受该权限, 默认为false .setPermissonCallback(new PermissionCallback() { @Override public void onPermissionGranted() { } @Override public void onPermissionReject() { } }).requestPermissions(); }

再来个必须强制授权的。

PermissionHelper.getInstance().with(this) .setPermissions(PermissionModel.READ_PHONE_STATE) .setRequestCode("4002") .setForceAccepting(true) //表示必须强制用户接受该权限, 默认为false .setPermissonCallback(new PermissionDetailCallback() { @Override public void onPermissionRejectNoPrompts(String[] permissions) { showPermissionDialog("未获取相关权限,不能使用该功能,是否去设置权限"); } @Override public void onPermissionGranted() { Intent intent = new Intent(getContext(), Abc.class); startActivity(intent); } } @Override public void onPermissionReject() { } }).requestPermissions();

此代码的逻辑是:当设置为强制授权时,普通拒绝的情况下,再次提示授权;当选中【拒绝后不再提示】的情况下拒绝,会提示去授权,直接跳转到设置权限的页面。

AlertDialog mPermissionDialog; / * 不再提示权限 时的展示对话框 */ private void showPermissionDialog(final int requestCode) { if (mPermissionDialog == null) { mPermissionDialog = new AlertDialog.Builder(this) .setMessage("已禁用权限,请手动授予") .setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mPermissionDialog.dismiss(); Uri packageURI = Uri.parse("package:" + getPackageName()); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI); startActivity(intent); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cancelPermissionDialog(); } }) .create(); } mPermissionDialog.show(); } private void cancelPermissionDialog() { if (mPermissionDialog != null && mPermissionDialog.isShowing()) { mPermissionDialog.dismiss(); } }

对了,最后一步,在需要请求权限的Activity中,重写onRequestPermissionsResult()方法。

@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { PermissionHelper.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults); } 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/149370.html

(0)
上一篇 2025-03-24 15:25
下一篇 2025-03-24 15:26

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信