Android PermissionUtils:运行时权限工具类及申请权限的正确姿势

PermissionUtil

经常写Android运行时权限申请代码,每次都是复制过来之后,改一下权限字符串就用,把代码搞得乱糟糟的,于是便有了封装工具类的想法,话不多说,先看怎么用:

工具类及Demo:github

简洁版申请权限

申请一个权限:

    PermissionUtils.checkAndRequestPermission(mContext, PERMISSION_CAMERA, REQUEST_CODE_CAMERA,
                new PermissionUtils.PermissionRequestSuccessCallBack() {
            @Override
            public void onHasPermission() {
                // 权限已被授予
                toCamera();
            }
        });

然后在onRequestPermissionsResult中:

if(PermissionUtils.isPermissionRequestSuccess(grantResults))
                {
                    // 权限申请成功
                    toCamera();
                }

什么?要同时申请多个权限?

    PermissionUtils.checkAndRequestMorePermissions(mContext, PERMISSIONS, REQUEST_CODE_PERMISSIONS,
                new PermissionUtils.PermissionRequestSuccessCallBack() {
            @Override
            public void onHasPermission() {
                // 权限已被授予
                toCamera();
            }
        });

当然上面这些都不是申请权限的正确姿势,理想的姿势应该是:

  • 第一次申请权限:按照正常流程走;
  • 如果用户第一次拒绝了权限申请,第二次申请时应向用户解释权限用途;
  • 如果用户勾选了“不再询问”选项,应引导用户去设置页手动开启权限。

如图:

第一次申请权限
第二次申请权限并禁止询问

于是,引申出了复杂版的权限申请方法:

自定义权限申请:

PermissionUtils.checkPermission(mContext, PERMISSION_CAMERA,
                new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                // 已授予权限
                toCamera();
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                // 上一次申请权限被拒绝,可用于向用户说明权限原因,然后调用权限申请方法。
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                // 第一次申请权限或被禁止申请权限,建议直接调用申请权限方法。
            }
        });

然后在onRequestPermissionsResult中:

PermissionUtils.onRequestPermissionResult(mContext, PERMISSION_CAMERA, grantResults, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        toCamera();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        Toast.makeText(mContext, "我们需要"+Arrays.toString(permission)+"权限", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Toast.makeText(mContext, "我们需要"+Arrays.toString(permission)+"权限", Toast.LENGTH_SHORT).show();
                        // 显示前往设置页的dialog
                        showToAppSettingDialog();
                    }
                });

基本使用就是这些了,包括前往应用设置页的方法,也在工具类里面,具体使用可以看demo。

工具类及Demo:github

贴一下工具类代码:

package com.fadai.library;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 *     author : FaDai
 *     e-mail : [email protected]
 *     time   : 2017/06/13
 *     desc   : xxxx描述
 *     version: 1.0
 * 
*/ public class PermissionUtils { /** * 检测权限 * * @return true:已授权; false:未授权; */ public static boolean checkPermission(Context context, String permission) { if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) return true; else return false; } /** * 检测多个权限 * * @return 未授权的权限 */ public static List checkMorePermissions(Context context, String[] permissions) { List permissionList = new ArrayList<>(); for (int i = 0; i < permissions.length; i++) { if (!checkPermission(context, permissions[i])) permissionList.add(permissions[i]); } return permissionList; } /** * 请求权限 */ public static void requestPermission(Context context, String permission, int requestCode) { ActivityCompat.requestPermissions((Activity) context, new String[]{permission}, requestCode); } /** * 请求多个权限 */ public static void requestMorePermissions(Context context, List permissionList, int requestCode) { String[] permissions = (String[]) permissionList.toArray(new String[permissionList.size()]); requestMorePermissions(context, permissions, requestCode); } /** * 请求多个权限 */ public static void requestMorePermissions(Context context, String[] permissions, int requestCode) { ActivityCompat.requestPermissions((Activity) context, permissions, requestCode); } /** * 判断是否已拒绝过权限 * * @return * @describe :如果应用之前请求过此权限但用户拒绝,此方法将返回 true; * -----------如果应用第一次请求权限或 用户在过去拒绝了权限请求, * -----------并在权限请求系统对话框中选择了 Don't ask again 选项,此方法将返回 false。 */ public static boolean judgePermission(Context context, String permission) { if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permission)) return true; else return false; } /** * 检测权限并请求权限:如果没有权限,则请求权限 */ public static void checkAndRequestPermission(Context context, String permission, int requestCode) { if (!checkPermission(context, permission)) { requestPermission(context, permission, requestCode); } } /** * 检测并请求多个权限 */ public static void checkAndRequestMorePermissions(Context context, String[] permissions, int requestCode) { List permissionList = checkMorePermissions(context, permissions); requestMorePermissions(context, permissionList, requestCode); } /** * 检测权限 * * @describe:具体实现由回调接口决定 */ public static void checkPermission(Context context, String permission, PermissionCheckCallBack callBack) { if (checkPermission(context, permission)) { // 用户已授予权限 callBack.onHasPermission(); } else { if (judgePermission(context, permission)) // 用户之前已拒绝过权限申请 callBack.onUserHasAlreadyTurnedDown(permission); else // 用户之前已拒绝并勾选了不在询问、用户第一次申请权限。 callBack.onUserHasAlreadyTurnedDownAndDontAsk(permission); } } /** * 检测多个权限 * * @describe:具体实现由回调接口决定 */ public static void checkMorePermissions(Context context, String[] permissions, PermissionCheckCallBack callBack) { List permissionList = checkMorePermissions(context, permissions); if (permissionList.size() == 0) { // 用户已授予权限 callBack.onHasPermission(); } else { boolean isFirst = true; for (int i = 0; i < permissionList.size(); i++) { String permission = permissionList.get(i); if (judgePermission(context, permission)) { isFirst = false; break; } } String[] unauthorizedMorePermissions = (String[]) permissionList.toArray(new String[permissionList.size()]); if (isFirst)// 用户之前已拒绝过权限申请 callBack.onUserHasAlreadyTurnedDownAndDontAsk(unauthorizedMorePermissions); else // 用户之前已拒绝并勾选了不在询问、用户第一次申请权限。 callBack.onUserHasAlreadyTurnedDown(unauthorizedMorePermissions); } } /** * 检测并申请权限 */ public static void checkAndRequestPermission(Context context, String permission, int requestCode, PermissionRequestSuccessCallBack callBack) { if (checkPermission(context, permission)) {// 用户已授予权限 callBack.onHasPermission(); } else { requestPermission(context, permission, requestCode); } } /** * 检测并申请多个权限 */ public static void checkAndRequestMorePermissions(Context context, String[] permissions, int requestCode, PermissionRequestSuccessCallBack callBack) { List permissionList = checkMorePermissions(context, permissions); if (permissionList.size() == 0) { // 用户已授予权限 callBack.onHasPermission(); } else { requestMorePermissions(context, permissionList, requestCode); } } /** * 判断权限是否申请成功 */ public static boolean isPermissionRequestSuccess(int[] grantResults) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) return true; else return false; } /** * 用户申请权限返回 */ public static void onRequestPermissionResult(Context context, String permission, int[] grantResults, PermissionCheckCallBack callback) { if (PermissionUtils.isPermissionRequestSuccess(grantResults)) { callback.onHasPermission(); } else { if (PermissionUtils.judgePermission(context, permission)) { callback.onUserHasAlreadyTurnedDown(permission); } else { callback.onUserHasAlreadyTurnedDownAndDontAsk(permission); } } } /** * 用户申请多个权限返回 */ public static void onRequestMorePermissionsResult(Context context, String[] permissions, PermissionCheckCallBack callback) { boolean isBannedPermission = false; List permissionList = checkMorePermissions(context, permissions); if (permissionList.size() == 0) callback.onHasPermission(); else { for (int i = 0; i < permissionList.size(); i++) { if (!judgePermission(context, permissionList.get(i))) { isBannedPermission = true; break; } } // 已禁止再次询问权限 if (isBannedPermission) callback.onUserHasAlreadyTurnedDownAndDontAsk(permissions); else // 拒绝权限 callback.onUserHasAlreadyTurnedDown(permissions); } } /** * 跳转到权限设置界面 */ public static void toAppSetting(Context context) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= 9) { intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.setData(Uri.fromParts("package", context.getPackageName(), null)); } else if (Build.VERSION.SDK_INT <= 8) { intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName()); } context.startActivity(intent); } public interface PermissionRequestSuccessCallBack { /** * 用户已授予权限 */ void onHasPermission(); } public interface PermissionCheckCallBack { /** * 用户已授予权限 */ void onHasPermission(); /** * 用户已拒绝过权限 * * @param permission:被拒绝的权限 */ void onUserHasAlreadyTurnedDown(String... permission); /** * 用户已拒绝过并且已勾选不再询问选项、用户第一次申请权限; * * @param permission:被拒绝的权限 */ void onUserHasAlreadyTurnedDownAndDontAsk(String... permission); } }

工具类及Demo:github

你可能感兴趣的:(Android PermissionUtils:运行时权限工具类及申请权限的正确姿势)