1 Star 1 Fork 7

kesionli / easypermission

forked from 张彦强 / easypermission 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

EasyPermission

README: 中文 | English

EasyPermission简介

  • 这个是一个方便Android中权限管理的库,它使得申请权限和业务代码逻辑简单分离,不去关心权限的申请和回调。
  • 将安卓动态权限的申请和判断简单到一句话就能完成:
    requestPermission(Manifest.permission.CAMERA)
  • 最新2.0版本主要更新:
  1. 增加了支持动态设置 PermissionAlertInfo (权限提示信息)
  2. 实现activity监控不在要求必须传入Activity,可在任意地方调用权限申请(Activity,Fragment,View,Service,BroadcastReceiver)
  3. 增加特殊权限处理工具及演示(通知栏、悬浮窗、定位服务)
  4. EasyPermissionResult回调中可直接调用 openAppDetails();
  5. 增加 setAutoOpenAppDetails,如果PermissionAlertInfo有值,则在被禁止时自动触发openAppDetails();
  6. 增加EasyAppSettingDialogStyle,说明弹窗支持自定义的文本颜色、大小、按钮文本和主题颜色等;

初衷

  • 以前你是怎么管理Android的权限的?
  1. 先判断有没有权限
  2. 再申请权限
  3. 最后onRequestPermissionsResult中检查一个个结果,再执行自己的业务逻辑?
  • 有一个打电话的权限,好多地方都要用,你每次使用打电话都要写一遍权限的判断申请和结果处理?
  • 应对最新隐私政策,请求权限时希望可以弹出功能说明对用户进行告知?
  • 那现在有一个好消息:
    这儿有一个方便Android中权限管理的库,你告诉它你需要的权限,然后再告诉它你想要执行什么,就可以了。

解释

  1. module-easypermissionlib是EasyPermission 的核心源码code;
  2. module-app是EasyPermission的一个使用demo;

集成方法

最新版本 最新版本

第一步. 添加JitPack

将其添加到根build.gradle中.

allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

第二步. 添加依赖

dependencies {
	        implementation 'com.gitee.zhang-yanqiang:easypermission:v2.0.15'
	}

第三步. 初始化配置

1.在Application的onCreate中完成初始化

 @Override
    public void onCreate() {
        super.onCreate();
        //首次使用权限申请之前完成初始化,建议放在Application onCreate()中完成
        EasyPermissionHelper.getInstance().init(this);
    }

2.将要使用EasyPermission的Activity中的onRequestPermissionsResultonActivityResult,

  • 在对应的Activity调用EasyPermissionHelper.getInstance().onRequestPermissionsResult和onActivityResult即可;
  • 如果你有BaseActivity,那么只需要在BaseActivity中设置一次即可。
  • 这两个方方法为了实现授权结果的自动回调,如果不需要回调可以不配置
 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //使用EasyPermissionHelper注入回调
        EasyPermissionHelper.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //使用EasyPermissionHelper注入回调
        EasyPermissionHelper.getInstance().onActivityResult(requestCode, resultCode, data);
    }

功能使用

接下来看下怎么使用。

1.检测权限

只需要调用EasyPermission的hasPermission方法,支持多个权限同时传入。

EasyPermission.build().hasPermission(Manifest.permission.CAMERA);

2.申请权限

如果你在应用启动时需要申请权限,而且并不关注权限的结果,
只需要调用EasyPermission的requestPermission方法,支持多个权限传入。

 EasyPermission.build().requestPermission(Manifest.permission.CAMERA);

3.需要权限的结果

  • 如果你需要知道申请权限后用户的选择结果,同时去执行自己的方法myVoid(),
  • 那么在onPermissionsAccess中去做就可以了,
  • onPermissionsDismiss是用户拒绝了权限的反馈。
 EasyPermission.build()
                .mRequestCode(RC_CODE_PERMISSION)
                .mPerms(Manifest.permission.CAMERA)
                .mResult(new EasyPermissionResult() {
                    @Override
                    public void onPermissionsAccess(int requestCode) {
                        super.onPermissionsAccess(requestCode);
                        //权限已通过
                    }

                    @Override
                    public void onPermissionsDismiss(int requestCode, @NonNull List<String> permissions) {
                        super.onPermissionsDismiss(requestCode, permissions);
                        //权限被拒绝
                    }
                }).requestPermission();

4.有时用户拒绝了权限,而且禁止了弹出询问,我该怎么办?想要在申请权限时弹窗告知用户权限的必要性怎么办?

  • 事实上,在新版本只需要通过mAlertInfo设置了提示文本,现在已经默认处理了弹窗的展示,也就是说不需要去重写onDismissAskopenAppDetails方法了
  • 只要在onDismissAsk中,就可以得到被禁止的结果,同时你要注意onDismissAsk默认返回false
  • 如果你自己修改return true,将视为已经处理了禁止结果,将不再回调onPermissionsDismiss这个方法
  • 调用openAppDetails方法,可以弹窗引导用户去设置界面设置权限,成功后会自动回调onPermissionsAccess
easyPermission = EasyPermission.build()
        .mRequestCode(RC_CODE_PERMISSION)
        .mPerms(Manifest.permission.CAMERA)
        .setAutoOpenAppDetails(true) //被拒绝并禁止时是否自动弹窗提醒,默认是true
        .mAlertInfo( new PermissionAlertInfo("**需要申请摄像头权限",
        "**需要申请摄像头拍摄权限,以便您能够通过扫一扫实现扫描二维码;通过拍照更换您帐号的头像;拍照上传一些注册帐号需要的证件信息。拒绝或取消授权将影响以上功能,不影响使用其他服务"))
        .mResult(new EasyPermissionResult() {
            @Override
            public void onPermissionsAccess(int requestCode) {
                super.onPermissionsAccess(requestCode);
                //权限已通过
            }

            @Override
            public void onPermissionsDismiss(int requestCode, @NonNull List<String> permissions) {
                super.onPermissionsDismiss(requestCode, permissions);
                //权限被拒绝
            }

            @Override
            public boolean onDismissAsk(int requestCode, @NonNull List<String> permissions) {
                //权限被拒绝并禁止再次询问
                return super.onDismissAsk(requestCode,permissions);//这里true表示拦截处理,不再回调onPermissionsDismiss;
            }
            @Override
            public void openAppDetails() {
                //弹出默认的权限详情设置提示弹出框,在设置页完成允许操作后,会自动回调到onPermissionsAccess()
                super.openAppDetails();
                //如果样式不满意,可以弹出自定义明弹窗,在用户确认时调用 goToAppSettings();完成跳转设置页
            }).requestPermission();

5.弹窗样式自定义

权限库用起来蛮方便的,但是弹窗的文字颜色需要改一下,又不像大动干戈地每次自己去写弹窗,能不能设置一下文字大小、颜色?没问题,咱们支持弹窗自定义样式。

使用默认经典样式(类似京东、小红书)

EasyPermissionHelper.getInstance().setDialogStyle(new EasyAppSettingDialogStyle(EasyAppSettingDialogStyle.DialogStyle.STYLE_DEFAULT));

使用系统自带弹窗样式

EasyPermissionHelper.getInstance().setDialogStyle(new EasyAppSettingDialogStyle(EasyAppSettingDialogStyle.DialogStyle.STYLE_SYSTEM));

使用自定义弹窗样式

EasyPermissionHelper.getInstance().setDialogStyle(
        new EasyAppSettingDialogStyle(EasyAppSettingDialogStyle.DialogStyle.STYLE_CUSTOM)
        .setTitleGravity(Gravity.CENTER)//设置居中
        .setTitleSize(17)//设置标题样式
        .setTitleColor("#333333")
        .setMessageSize(14)//设置内容样式
        .setMessageColor("#666666")
        .setButtonTextSize(14)//设置按钮样式
        .setButtonThemeColor("#FF0000")
        .setCancelText("取消")//设置按钮文本
        .setConfirmText("去打开"));

完全自定义弹窗

以上方式只需要在初始话后设置一次,全局生效。如果以上方式依然满足不了你胃口,那只能自己去控制弹窗拉。
EasyPermissionResult中重写openAppDetails

 @Override
public void openAppDetails() {
      //在前往应用设置详情页展示自己的弹窗告知用户我们需要哪些权限打开
      //在用户点击确认时调用easyPermission.goToAppSettings();完成跳转设置页
      }

6.顶部提示信息样式自定义

权限库用起来蛮方便的,但是顶部提示的背景颜色需要改一下,能不能设置一下文字大小、颜色、背景色?没问题,咱们支持顶部提示信息自定义样式。

使用默认经典样式

EasyPermissionHelper.getInstance().setTopAlertStyle(
        new EasyTopAlertStyle(EasyTopAlertStyle.AlertStyle.STYLE_DEFAULT));

使用自定义提示样式

EasyPermissionHelper.getInstance().setTopAlertStyle(
        new EasyTopAlertStyle(EasyTopAlertStyle.AlertStyle.STYLE_CUSTOM)
        .setTitleGravity(Gravity.LEFT)//默认居左
        .setTitleSize(16)//设置标题样式,默认16sp
        .setTitleColor("#333333")
        .setMessageSize(14)//设置内容样式,默认14sp
        .setMessageColor("#333333")
        .setBackgroundColor("#FFFFFF")//设置背景色,默认白色
        .setBackgroundRadius(8)//设置背景圆角弧度,默认8dp
        .setBackgroundElevation(6)//设置背景阴影范围,默认6dp
        .setTopMargin(10)//设置距离顶部标题栏间距,默认10dp
        .setSideMargin(10));//设置距离屏幕两边宽度,默认10dp

7.其它注意事项

  1. mAlertInfo不设置将不会自动弹出权限说明弹窗,为了满足当前的日益严格的隐私政策,请对认真对待每一个权限说明
  2. 权限的申请不建议在onNewIntent中获取
  3. 相关日志tag为"EasyPermissionLog",默认不输出太多信息,如果需要调试请打开EasyPermissionConfigs.setDebug(true)
  4. 增加setAutoOpenAppDetails,如果PermissionAlertInfo有值,则在被禁止时自动触发 openAppDetails()
  5. 如果openAppDetails()样式不满足,可以重写openAppDetails()自定义弹出内容,也可以直接在onDismissAsk()拦截
  6. 由于EasyPermission在init初始化时使用ActivityLifecycleCallbacks开始监听activity变化,所以在launchMode="singleTask" onNewIntent中如果需要请求权限,需要重新设置activity。 可以使用两种方式完成。

方式一:

EasyPermissionHelper.getInstance().updateTopActivity(mContext);
easyPermission.requestPermission();

方式二:

easyPermission.mContext(mContext).requestPermission();

8.其它工具

定位服务管理 EasyLocationTool

Android 9.0以后即使已经获得了用户授权定位权限,由于GPS定位服务未打开,依然获取不到定位,所以还需要对定位服务进行处理,LocationTool支持以下方法:

  1. isLocationEnabled() 获取当前定位服务是否开启
  2. gotoAppSettings() 直接跳转到手机-设置-安全和隐私-定位服务开启/关闭的页面

通知服务管理 EasyNotificationTool

通知服务的权限在Android中也比较特殊,它不像其它权限那样去直接申请,像定位服务一样需要去系统设置中开启,所以也要去设置页:

  1. isNotificationEnabled() 获取当前APP的通知权限是否开启
  2. gotoAppSettings() 直接跳转到手机-设置-通知和状态栏-通知管理-APP通知设置页

悬浮窗权限管理 EasyFloatWindowTool

悬浮窗权限在Android中也比较特殊,它不像其它权限那样去直接申请,像定位服务一样需要去系统设置中开启,所以也要去设置页:

  1. isFloatWindowEnabled() 获取当前APP的是否有悬浮窗权限
  2. gotoAppSettings() 直接跳转到手机-设置-应用管理-特殊应用权限-显示在其他应用的上层-APP设置页

结束语

  • 如果又更好的方案和思路,欢迎留言或者私信
  • 祝所有人平安幸福、家庭和睦、身体健康。
  • 愿祖国早日完成统一大业,世界和平共处,繁荣发展。
  • 有任何疑问,可以及时反馈给我;
  • 如果你觉得还不错,请点赞o( ̄▽ ̄)d。
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

这个是一个方便Android中权限管理的库,它使得申请权限和业务代码逻辑简单分离,不去关心权限的申请和回调。 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/lgsg/easypermission.git
git@gitee.com:lgsg/easypermission.git
lgsg
easypermission
easypermission
master

搜索帮助