程序员干货Android开发Android技术知识

Android动态权限的封装

2018-11-02  本文已影响22人  半岛铁盒1979
  1. Android权限的分类:

       正常权限和危险权限

       从 Android 6.0(API 级别 23)开始,用户开始在应用运行时向其授予权限,而不是在应用安装时授予。此方法可以简化应用安装过程,因为用户在安装或更新应用时不需要授予权限。它还让用户可以对应用的功能进行更多控制

  1. 为什么要进行动态权限的配置:

       谷歌官方处于安全考虑,让用户能够自己选择是否需要再APP内进行授权,避免了很多流氓软件

  1. 哪些是危险权限:
危险权限.png 危险权限.png

ps:属于同一组的权限不用重复授权

  1. 申请危险权限相关的方法:
//申请对应的权限
ActivityCompat.requestPermissions(final Activity activity,
            final String[] permissions, final int requestCode) 
//申请结果回调方法
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
//判断用户是否勾选了不再提醒
//如果拒绝了该权限,并勾选了不再提醒返回false
@Override
ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])
  1. 封装的Activity:
//判断用户是否勾选了不再提醒
//如果拒绝了该权限,并勾选了不再提醒返回false
/**
 * 类名: PermissionActivity
 * 描述: 动态权限的封装
 * 日期: 2018/10/30
 *
 * @author: liuqiyuan
 */

public class PermissionActivity extends BaseActivity {

    private OnPermissionListener permissionListener = null;
    private static final int PERMISSION_REQ = 10;

    /**
     * 申请权限
     *
     * @param permissions          请求权限
     * @param onPermissionListener 回调函数
     */
    public void reqPermission(String[] permissions, OnPermissionListener onPermissionListener) {
        if (permissions == null || onPermissionListener == null) {
            return;
        }
        this.permissionListener = onPermissionListener;
        //6.0以下不需要申请权限
        if (Build.VERSION.SDK_INT < 23 || permissions.length == 0) {
            onPermissionListener.onGranted();
        } else {
            List<String> permissionList = new ArrayList<>();
            for (String permission : permissions) {
                //校验之前是否添加过权限
                if (ContextCompat.checkSelfPermission(this, permission)
                        == PackageManager.PERMISSION_GRANTED) {
                    continue;
                }
                permissionList.add(permission);
            }
            //权限全部都已授权
            if (permissionList.isEmpty()) {
                onPermissionListener.onGranted();
                return;
            }
            //请求权限
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), PERMISSION_REQ);
        }
    }

    /**
     * 申请权限的回调用
     *
     * @param requestCode  请求码
     * @param permissions  申请的权限
     * @param grantResults 授权结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != PERMISSION_REQ) {
            return;
        }
        if (grantResults.length == 0) {
            return;
        }
        int length = permissions.length;
        //循环判断授权结果
        for (int i = 0; i < length; i++) {
            //授权成功
            if (grantResults[i] == getPackageManager().PERMISSION_GRANTED) {
                continue;
            }
            //用户勾选了"不再提醒",会返回false,需引导用户手动开启权限
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                showReqPermissionDialog();
            } else {
                permissionListener.onDenied();
            }
            return;
        }
        permissionListener.onGranted();
    }

    /**
     * 提示用户手动开启权限
     */
    private void showReqPermissionDialog() {
        new AlertDialog.Builder(this)
                .setMessage("需要开启权限才能使用此功能")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        goToAppInfo();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.cancel();
                        permissionListener.onDenied();
                    }
                })
                .create()
                .show();
    }

    /**
     * 跳转系统的App应用信息页面
     */
    protected void goToAppInfo() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(localIntent);
    }
}

/**
 * 类名: OnPermissionListener
 * 描述: 权限申请结果回调
 * 日期: 2018/10/30
 *
 * @author: liuqiyuan
 */

public interface OnPermissionListener {

    /**
     * 已授权
     */
    void onGranted();

    /**
     * 授权失败
     */
    void onDenied();
}
  1. 测试的Activity:
public class MainActivity extends PermissionActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button btnPic = new Button(this);
        btnPic.setText("拍照");
        Button btnCall = new Button(this);
        btnCall.setText("打电话");
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(btnPic);
        ll.addView(btnCall);
        setContentView(ll);

        btnPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqPermission(new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.CAMERA}, new OnPermissionListener() {
                    @Override
                    public void onGranted() {
                        tackPic();
                    }

                    @Override
                    public void onDenied() {
                        Toast.makeText(MainActivity.this, "请允许添加权限", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        btnCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqPermission(new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.CAMERA}, new OnPermissionListener() {
                    @Override
                    public void onGranted() {
                        call();
                    }

                    @Override
                    public void onDenied() {
                        Toast.makeText(MainActivity.this, "请允许添加权限", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void tackPic() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void call() {
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri uri = Uri.parse("tel:" + "10010");
            intent.setData(uri);
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }
}
  1. 效果图:
允许申请权限.gif 拒绝申请权限.gif
上一篇下一篇

猜你喜欢

热点阅读