EasyPermission是一个简易的权限请求库。
使用方法
在程序入口的Activity中的onCreate方法中初始化它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
EasyPermission.initialize(this);
}
初始化后可以在任意时候请求权限.
EasyPermission.checkPermissions(new PermissionListener() {
@Override
public void onAllGranted() {
Log.d(TAG, "onAllGranted: ");
}
@Override
public void atLeastOneDenied(List<String> deniedPermissions, List<String> grantedPermissions) {
Log.d(TAG, "atLeastOneDenied: denied: ");
Log.d(TAG, "atLeastOneDenied: ###########################");
for (String denied : deniedPermissions) {
Log.d(TAG, "atLeastOneDenied: " + denied);
}
Log.d(TAG, "atLeastOneDenied: granted: ");
Log.d(TAG, "atLeastOneDenied: ###########################");
for (String granted : grantedPermissions) {
Log.d(TAG, "atLeastOneDenied: " + granted);
}
// Activity的onResume尚未回掉,不能直接弹出部分dialog
// showPermissionDeniedDialog(deniedPermissions);
}
}, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
如果有在被拒绝权限时显示自定义的DialogFragment的需求或者是希望onResume被回掉之后,权限的请求结果再被回调,可以使用以下方法:
private EasyPermissionHelper permissionHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
permissionHelper = new EasyPermissionHelper(this);
}
@Override
protected void onResume() {
super.onResume();
permissionHelper.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
permissionHelper.onDestroy();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void doRequest() {
permissionHelper.checkPermissions(new PermissionListener() {
@Override
public void onAllGranted() {
}
@Override
public void atLeastOneDenied(List<String> deniedPermissions, List<String> grantedPermissions) {
// 此处回调是在onResume之后,可以直接显示DialogFragment
showPermissionDeniedDialog(deniedPermissions);
}
}, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
-
EasyPermission.initialize
和EasyPermission.checkPermissions
方法不再适用于这种情况. - 以上写法可以写在基类中方便调用
添加依赖到项目
- 在项目根目录的build.gradle添加
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
- 添加依赖
dependencies {
compile 'com.github.billy96322:EasyPermission:0.0.1'
}