diff --git a/README.md b/README.md index 198d34c..1ed0690 100644 --- a/README.md +++ b/README.md @@ -2,26 +2,14 @@ ![](XXPermissions.gif) -#### 集成步骤 +>[点击此处下载Demo](https://raw.githubusercontent.com/getActivity/XXPermissions/master/XXPermissions.apk) -> 在Module工程的build.gradle文件中添加依赖 +#### 集成步骤 dependencies { compile 'com.hjq:xxpermissions:1.0' } -> 如果导入失败,请检查在Project工程的build.gradle文件的配置 - - allprojects { - - repositories { - //添加对JCenter仓库的支持 - jcenter() - ...... - } - ...... - } - #### 一句代码搞定权限请求,从未如此简单 XXPermissions.with(this) @@ -34,9 +22,8 @@ } @Override - public void noPermission(List denied, boolean permanent) { + public void noPermission(List denied, boolean quick) { } }); - diff --git a/XXPermissions.apk b/XXPermissions.apk new file mode 100644 index 0000000..b49d17f Binary files /dev/null and b/XXPermissions.apk differ diff --git a/app-debug.apk b/app-debug.apk deleted file mode 100644 index ac712be..0000000 Binary files a/app-debug.apk and /dev/null differ diff --git a/app/src/main/java/com/hjq/permissions/demo/MainActivity.java b/app/src/main/java/com/hjq/permissions/demo/MainActivity.java index 916d1c5..bad6a33 100644 --- a/app/src/main/java/com/hjq/permissions/demo/MainActivity.java +++ b/app/src/main/java/com/hjq/permissions/demo/MainActivity.java @@ -31,8 +31,8 @@ public void hasPermission(List granted) { } @Override - public void noPermission(List denied, boolean permanent) { - if(permanent) { + public void noPermission(List denied, boolean quick) { + if(quick) { Toast.makeText(MainActivity.this, "被永久拒绝授权,请手动授予权限", Toast.LENGTH_SHORT).show(); //如果是被永久拒绝就跳转到应用权限系统设置页面 PermissionUtils.gotoPermissionSettings(MainActivity.this); diff --git a/library/.gitignore b/library/.gitignore index 796b96d..3543521 100644 --- a/library/.gitignore +++ b/library/.gitignore @@ -1 +1 @@ -/build +/build diff --git a/library/build.gradle b/library/build.gradle index 2cbf913..9ad433f 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -1,131 +1,131 @@ -//文件开头配置 -apply plugin: 'com.android.library' -apply plugin: 'com.jfrog.bintray' -apply plugin: 'com.github.dcendents.android-maven' - -android { - compileSdkVersion 25 - buildToolsVersion "25.0.3" - - defaultConfig { - minSdkVersion 11 - targetSdkVersion 25 - versionCode 1 - versionName "1.0" - } -} - -def siteUrl = 'https://github.com/getActivity/XXPermissions' //项目在github中的地址 -def gitUrl = siteUrl + ".git" //项目在github中的地址 - -//compile 'com.hjq:xxpermissions:1.0' -def groupId = 'com.hjq' //定义的maven group id最终引用形式 -def artifactId = 'xxpermissions'//maven的artifact id,不要带大写,可以用“-”代替 -def versionName = '1.0'//maven 上发布版本号 - -def repositoryName = 'maven' //自己创建的仓库名,直接在bintray账号下创建的 -def repositoryDesc = 'Android 6.0 permissions adaptation framework' //仓库描述,自己定义 -def packageName = 'XXPermissions' //在仓库创建的包名称,在maven jcenter上显示的名字,最终引用的名字 - -def idName = 'getactivity' //填写bintray用户名,注意大小写 -def orgName = idName //自己的organization(组织)名称,这里的组织直接就是自己的用户名 -def developerName = 'huangjinqun' //开发者姓名 -def developerEmail = 'jinqun0730@gmail.com' //开发者邮箱 - -def licensesName = 'Apache-2.0' //不能随便写,只能是仓库创建时选择的license type -def licensesUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt' //协议地址 - -def codedFormat = 'UTF-8'//如果你的项目里面有中文注释的话,必须将格式设置为UTF-8,不然会出现乱码 -def packagingType = 'aar'//打包类型,可以打包成aar也可以打包成jar,本质上都是zip包 - -Properties properties = new Properties() -properties.load(project.rootProject.file('local.properties').newDataInputStream()) - -//Gradle配置 -version = versionName -group = groupId -bintray { - user = properties.getProperty('bintray.user') - key = properties.getProperty('bintray.apikey') - pkg { - repo = repositoryName - name = packageName - websiteUrl = siteUrl - vcsUrl = gitUrl - licenses = [licensesName] - userOrg = orgName - publish = true // 是否是公开项目,公开别人可以引用 - version { - name = versionName - desc = repositoryDesc - released = new Date() - vcsTag = 'v1.0' - attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin'] - } - } - configurations = ['archives'] -} - -install { - repositories.mavenInstaller { - // This generates POM.xml with proper parameters - pom { - project { - packaging packagingType - name artifactId - description repositoryDesc - url siteUrl - // Set your license - licenses { - license { - name licensesName - url licensesUrl - } - } - developers { - developer { - id idName - name developerName - email developerEmail - } - } - scm { - connection gitUrl - developerConnection gitUrl - url siteUrl - } - } - } - } -} - -task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' -} - -task javadoc(type: Javadoc) { - failOnError false //必须添加以免出错 - source = android.sourceSets.main.java.srcDirs - classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) -} - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -artifacts { - archives javadocJar - archives sourcesJar -} - -javadoc { - options { - encoding codedFormat - charSet codedFormat - author true - version true - links 'http://docs.oracle.com/javase/7/docs/api' - } +//文件开头配置 +apply plugin: 'com.android.library' +apply plugin: 'com.jfrog.bintray' +apply plugin: 'com.github.dcendents.android-maven' + +android { + compileSdkVersion 25 + buildToolsVersion "25.0.3" + + defaultConfig { + minSdkVersion 11 + targetSdkVersion 25 + versionCode 2 + versionName "1.1" + } +} + +def siteUrl = 'https://github.com/getActivity/XXPermissions' //项目在github中的地址 +def gitUrl = siteUrl + ".git" //项目在github中的地址 + +//compile 'com.hjq:xxpermissions:1.1' +def groupId = 'com.hjq' //定义的maven group id最终引用形式 +def artifactId = 'xxpermissions'//maven的artifact id,不要带大写,可以用“-”代替 +def versionName = '1.1'//maven 上发布版本号 + +def repositoryName = 'maven' //自己创建的仓库名,直接在bintray账号下创建的 +def repositoryDesc = 'Android 6.0 permissions adaptation framework' //仓库描述,自己定义 +def packageName = 'XXPermissions' //在仓库创建的包名称,在maven jcenter上显示的名字,最终引用的名字 + +def idName = 'getactivity' //填写bintray用户名,注意大小写 +def orgName = idName //自己的organization(组织)名称,这里的组织直接就是自己的用户名 +def developerName = 'huangjinqun' //开发者姓名 +def developerEmail = 'jinqun0730@gmail.com' //开发者邮箱 + +def licensesName = 'Apache-2.0' //不能随便写,只能是仓库创建时选择的license type +def licensesUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt' //协议地址 + +def codedFormat = 'UTF-8'//如果你的项目里面有中文注释的话,必须将格式设置为UTF-8,不然会出现乱码 +def packagingType = 'aar'//打包类型,可以打包成aar也可以打包成jar,本质上都是zip包 + +Properties properties = new Properties() +properties.load(project.rootProject.file('local.properties').newDataInputStream()) + +//Gradle配置 +version = versionName +group = groupId +bintray { + user = properties.getProperty('bintray.user') + key = properties.getProperty('bintray.apikey') + pkg { + repo = repositoryName + name = packageName + websiteUrl = siteUrl + vcsUrl = gitUrl + licenses = [licensesName] + userOrg = orgName + publish = true // 是否是公开项目,公开别人可以引用 + version { + name = versionName + desc = repositoryDesc + released = new Date() + vcsTag = 'v1.0' + attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin'] + } + } + configurations = ['archives'] +} + +install { + repositories.mavenInstaller { + // This generates POM.xml with proper parameters + pom { + project { + packaging packagingType + name artifactId + description repositoryDesc + url siteUrl + // Set your license + licenses { + license { + name licensesName + url licensesUrl + } + } + developers { + developer { + id idName + name developerName + email developerEmail + } + } + scm { + connection gitUrl + developerConnection gitUrl + url siteUrl + } + } + } + } +} + +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +task javadoc(type: Javadoc) { + failOnError false //必须添加以免出错 + source = android.sourceSets.main.java.srcDirs + classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} + +artifacts { + archives javadocJar + archives sourcesJar +} + +javadoc { + options { + encoding codedFormat + charSet codedFormat + author true + version true + links 'http://docs.oracle.com/javase/7/docs/api' + } } \ No newline at end of file diff --git a/library/src/main/java/com/hjq/permissions/OnPermission.java b/library/src/main/java/com/hjq/permissions/OnPermission.java index e60d6ad..a5f14ac 100644 --- a/library/src/main/java/com/hjq/permissions/OnPermission.java +++ b/library/src/main/java/com/hjq/permissions/OnPermission.java @@ -1,24 +1,24 @@ -package com.hjq.permissions; - -import java.util.List; - -/** - * Created by HJQ on 2018-6-15. - */ -public interface OnPermission { - - /** - * 有权限被授予时回调 - * - * @param granted 请求成功的权限组 - */ - void hasPermission(List granted); - - /** - * 有权限被拒绝授予时回调 - * - * @param denied 请求失败的权限组 - * @param permanent 是否永久拒绝了 - */ - void noPermission(List denied, boolean permanent); +package com.hjq.permissions; + +import java.util.List; + +/** + * Created by HJQ on 2018-6-15. + */ +public interface OnPermission { + + /** + * 有权限被授予时回调 + * + * @param granted 请求成功的权限组 + */ + void hasPermission(List granted); + + /** + * 有权限被拒绝授予时回调 + * + * @param denied 请求失败的权限组 + * @param quick 是否永久拒绝了 + */ + void noPermission(List denied, boolean quick); } \ No newline at end of file diff --git a/library/src/main/java/com/hjq/permissions/PermissionFragment.java b/library/src/main/java/com/hjq/permissions/PermissionFragment.java index f55c421..3fa7044 100644 --- a/library/src/main/java/com/hjq/permissions/PermissionFragment.java +++ b/library/src/main/java/com/hjq/permissions/PermissionFragment.java @@ -1,49 +1,49 @@ -package com.hjq.permissions; - -import android.app.Fragment; -import android.app.FragmentManager; -import android.app.FragmentTransaction; -import android.os.Bundle; - -import java.util.ArrayList; - -/** - * Created by HJQ on 2018-6-15. - */ -public final class PermissionFragment extends Fragment { - - private static final String PERMISSIONS = "permissions"; - private static final String REQUEST_CODE ="request_code"; - - public static PermissionFragment newInstant(ArrayList permissions, int requestCode) { - PermissionFragment fragment = new PermissionFragment(); - Bundle bundle = new Bundle(); - bundle.putStringArrayList(PERMISSIONS, permissions); - bundle.putInt(REQUEST_CODE, requestCode); - fragment.setArguments(bundle); - return fragment; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (PermissionUtils.isOverMarshmallow()) { - ArrayList permissions = getArguments().getStringArrayList(PERMISSIONS); - requestPermissions(permissions.toArray(new String[permissions.size() - 1]), getArguments().getInt(REQUEST_CODE)); - } - } - - @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { - XXPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults); - FragmentTransaction ft = getFragmentManager().beginTransaction(); - ft.remove(this); - ft.commit(); - } - - public void request(FragmentManager manager) { - FragmentTransaction ft = manager.beginTransaction(); - ft.add(this, this.getClass().getName()); - ft.commit(); - } +package com.hjq.permissions; + +import android.app.Fragment; +import android.app.FragmentManager; +import android.app.FragmentTransaction; +import android.os.Bundle; + +import java.util.ArrayList; + +/** + * Created by HJQ on 2018-6-15. + */ +public final class PermissionFragment extends Fragment { + + private static final String PERMISSIONS = "permissions"; + private static final String REQUEST_CODE ="request_code"; + + public static PermissionFragment newInstant(ArrayList permissions, int requestCode) { + PermissionFragment fragment = new PermissionFragment(); + Bundle bundle = new Bundle(); + bundle.putStringArrayList(PERMISSIONS, permissions); + bundle.putInt(REQUEST_CODE, requestCode); + fragment.setArguments(bundle); + return fragment; + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + if (PermissionUtils.isOverMarshmallow()) { + ArrayList permissions = getArguments().getStringArrayList(PERMISSIONS); + requestPermissions(permissions.toArray(new String[permissions.size() - 1]), getArguments().getInt(REQUEST_CODE)); + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + XXPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults); + FragmentTransaction ft = getFragmentManager().beginTransaction(); + ft.remove(this); + ft.commit(); + } + + public void request(FragmentManager manager) { + FragmentTransaction ft = manager.beginTransaction(); + ft.add(this, this.getClass().getName()); + ft.commit(); + } } \ No newline at end of file diff --git a/library/src/main/java/com/hjq/permissions/PermissionUtils.java b/library/src/main/java/com/hjq/permissions/PermissionUtils.java index 2b2aae7..dbaf2d4 100644 --- a/library/src/main/java/com/hjq/permissions/PermissionUtils.java +++ b/library/src/main/java/com/hjq/permissions/PermissionUtils.java @@ -1,150 +1,161 @@ -package com.hjq.permissions; - -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.provider.Settings; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static android.R.attr.permission; - -/** - * Created by HJQ on 2018-6-15. - */ -public final class PermissionUtils { - - /** - * 不能被实例化 - */ - private PermissionUtils() {} - - /** - * 跳转到应用权限设置页面 - * - * @param context 上下文对象 - */ - public static void gotoPermissionSettings(Context context) { - Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); - //创建一个新栈存放,用户点击授予权限,会导致返回后不会重新创建Activity - //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - Uri uri = Uri.fromParts("package", context.getPackageName(), null); - intent.setData(uri); - context.startActivity(intent); - } - - /** - * 检查某些权限是否全部授予了 - * - * @param context 上下文对象 - * @param permissions 需要请求的权限组 - */ - public static boolean isHasPermission(Context context, String... permissions) { - return getFailPermissions(context, permissions).isEmpty(); - } - - /** - * 返回应用程序在清单文件中注册的权限 - */ - public static String[] getPermissions(Context context) { - PackageManager pm = context.getPackageManager(); - try { - return pm.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS).requestedPermissions; - } catch (PackageManager.NameNotFoundException e) { - return null; - } - } - - /** - * 是否是6.0以上版本 - */ - public static boolean isOverMarshmallow() { - return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; - } - - /** - * 获取没有授予的权限 - * - * @param context 上下文对象 - * @param permissions 需要请求的权限组 - */ - static ArrayList getFailPermissions(Context context, String[] permissions) { - - //如果是安卓6.0以下版本就返回一个长度为零的数组 - if(!PermissionUtils.isOverMarshmallow()) { - return new ArrayList<>(); - } - - ArrayList failPermissions = new ArrayList<>(); - for (String permission : permissions) { - //把没有授予过的权限加入到集合中 - if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED){ - failPermissions.add(permission); - } - } - return failPermissions; - } - - /** - * 获取没有授予的权限 - * - * @param permissions 需要请求的权限组 - * @param grantResults 允许结果组 - */ - static List getFailPermissions(String[] permissions, int[] grantResults) { - List failPermissions = new ArrayList<>(); - for (int i = 0; i < grantResults.length ; i++) { - - //把没有授予过的权限加入到集合中,-1表示没有授予,0表示已经授予 - if (grantResults[i] == PackageManager.PERMISSION_DENIED) { - failPermissions.add(permissions[i]); - } - } - return failPermissions; - } - - /** - * 获取已授予的权限 - * - * @param permissions 需要请求的权限组 - * @param grantResults 允许结果组 - */ - static List getSucceedPermissions(String[] permissions, int[] grantResults) { - - List succeedPermissions = new ArrayList<>(); - for (int i = 0; i < grantResults.length ; i++) { - - //把授予过的权限加入到集合中,-1表示没有授予,0表示已经授予 - if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { - succeedPermissions.add(permissions[i]); - } - } - return succeedPermissions; - } - - /** - * 检测权限有没有在清单文件中注册 - * - * @param activity Activity对象 - * @param requestPermissions 请求的权限组 - */ - static void checkPermissions(Activity activity, String[] requestPermissions) { - String[] permissions = PermissionUtils.getPermissions(activity); - if (permissions != null && permissions.length != 0) { - List manifest = Arrays.asList(permissions); - for (String permission : requestPermissions) { - if (!manifest.contains(permission)) { - throw new IllegalArgumentException(permission + ": Permissions are not registered in the manifest file"); - } - } - }else { - throw new IllegalArgumentException("Permissions are not registered in the manifest file"); - } - } -} +package com.hjq.permissions; + +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.provider.Settings; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static android.R.attr.permission; + +/** + * Created by HJQ on 2018-6-15. + */ +public final class PermissionUtils { + + /** + * 不能被实例化 + */ + private PermissionUtils() {} + + /** + * 跳转到应用权限设置页面 + * + * @param context 上下文对象 + */ + public static void gotoPermissionSettings(Context context) { + gotoPermissionSettings(context, false); + } + + /** + * 跳转到应用权限设置页面 + * + * @param context 上下文对象 + * @param newTask 是否使用新的任务栈启动 + */ + public static void gotoPermissionSettings(Context context, boolean newTask) { + Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); + //创建一个新栈存放,用户在系统设置授予权限后,会导致返回后不会重新创建当前Activity,不推荐这种做法 + if (newTask) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + intent.setData(Uri.fromParts("package", context.getPackageName(), null)); + context.startActivity(intent); + } + + /** + * 检查某些权限是否全部授予了 + * + * @param context 上下文对象 + * @param permissions 需要请求的权限组 + */ + public static boolean isHasPermission(Context context, String... permissions) { + return getFailPermissions(context, permissions).isEmpty(); + } + + /** + * 返回应用程序在清单文件中注册的权限 + */ + public static String[] getPermissions(Context context) { + PackageManager pm = context.getPackageManager(); + try { + return pm.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS).requestedPermissions; + } catch (PackageManager.NameNotFoundException e) { + return null; + } + } + + /** + * 是否是6.0以上版本 + */ + public static boolean isOverMarshmallow() { + return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; + } + + /** + * 获取没有授予的权限 + * + * @param context 上下文对象 + * @param permissions 需要请求的权限组 + */ + static ArrayList getFailPermissions(Context context, String[] permissions) { + + //如果是安卓6.0以下版本就返回一个长度为零的数组 + if(!PermissionUtils.isOverMarshmallow()) { + return new ArrayList<>(); + } + + ArrayList failPermissions = new ArrayList<>(); + for (String permission : permissions) { + //把没有授予过的权限加入到集合中 + if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED){ + failPermissions.add(permission); + } + } + return failPermissions; + } + + /** + * 获取没有授予的权限 + * + * @param permissions 需要请求的权限组 + * @param grantResults 允许结果组 + */ + static List getFailPermissions(String[] permissions, int[] grantResults) { + List failPermissions = new ArrayList<>(); + for (int i = 0; i < grantResults.length ; i++) { + + //把没有授予过的权限加入到集合中,-1表示没有授予,0表示已经授予 + if (grantResults[i] == PackageManager.PERMISSION_DENIED) { + failPermissions.add(permissions[i]); + } + } + return failPermissions; + } + + /** + * 获取已授予的权限 + * + * @param permissions 需要请求的权限组 + * @param grantResults 允许结果组 + */ + static List getSucceedPermissions(String[] permissions, int[] grantResults) { + + List succeedPermissions = new ArrayList<>(); + for (int i = 0; i < grantResults.length ; i++) { + + //把授予过的权限加入到集合中,-1表示没有授予,0表示已经授予 + if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { + succeedPermissions.add(permissions[i]); + } + } + return succeedPermissions; + } + + /** + * 检测权限有没有在清单文件中注册 + * + * @param activity Activity对象 + * @param requestPermissions 请求的权限组 + */ + static void checkPermissions(Activity activity, String[] requestPermissions) { + String[] permissions = PermissionUtils.getPermissions(activity); + if (permissions != null && permissions.length != 0) { + List manifest = Arrays.asList(permissions); + for (String permission : requestPermissions) { + if (!manifest.contains(permission)) { + throw new IllegalArgumentException(permission + ": Permissions are not registered in the manifest file"); + } + } + }else { + throw new IllegalArgumentException("Permissions are not registered in the manifest file"); + } + } +} diff --git a/library/src/main/java/com/hjq/permissions/XXPermissions.java b/library/src/main/java/com/hjq/permissions/XXPermissions.java index 1549929..5f05e53 100644 --- a/library/src/main/java/com/hjq/permissions/XXPermissions.java +++ b/library/src/main/java/com/hjq/permissions/XXPermissions.java @@ -1,120 +1,122 @@ -package com.hjq.permissions; - -import android.app.Activity; -import android.util.SparseArray; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; - -/** - * Created by HJQ on 2018-6-15. - */ -public final class XXPermissions { - - private final static SparseArray mContainer = new SparseArray<>(); - - private static long requestTime; - - private Activity mActivity; - private String[] mPermissions; - - /** - * 不能被外部实例化 - */ - private XXPermissions(Activity activity) { - this.mActivity = activity; - } - - /** - * 设置请求的对象 - */ - public static XXPermissions with(Activity activity) { - return new XXPermissions(activity); - } - - /** - * 设置权限组 - */ - public XXPermissions permission(String... permissions){ - this.mPermissions = permissions; - return this; - } - - /** - * 设置权限组 - */ - public XXPermissions permission(String[]... permissions){ - List permissionList = new ArrayList<>(); - for (String[] group : permissions) { - permissionList.addAll(Arrays.asList(group)); - } - this.mPermissions = permissionList.toArray(new String[permissionList.size() - 1]); - return this; - } - - /** - * 请求权限 - */ - public void request(OnPermission call) { - //如果没有指定请求的权限,就使用清单注册的权限进行请求 - if (mPermissions == null || mPermissions.length == 0) this.mPermissions = PermissionUtils.getPermissions(mActivity); - if (mPermissions == null || mPermissions.length == 0) throw new IllegalArgumentException("The requested permission cannot be empty"); - if (mActivity == null || mActivity.isFinishing()) throw new IllegalArgumentException("Illegal Activity was passed in"); - if (call == null) throw new IllegalArgumentException("The permission request callback interface must be implemented"); - - int requestCode; - - //请求码随机生成,避免随机产生之前的请求码,必须进行循环判断 - do { - //requestCode = new Random().nextInt(65535);//Studio编译的APK请求码必须小于65536 - requestCode = new Random().nextInt(255);//Eclipse编译的APK请求码必须小于256 - } while (mContainer.get(requestCode) != null); - - ArrayList failPermissions = PermissionUtils.getFailPermissions(mActivity, mPermissions); - - if (failPermissions.isEmpty()) { - //证明权限已经全部授予过 - call.hasPermission(Arrays.asList(mPermissions)); - } else { - //将当前的请求码和对象添加到集合中 - mContainer.put(requestCode, call); - //记录本次申请时间 - requestTime = System.currentTimeMillis(); - //检测权限有没有在清单文件中注册 - PermissionUtils.checkPermissions(mActivity, mPermissions); - //申请没有授予过的权限 - PermissionFragment.newInstant(failPermissions, requestCode).request(mActivity.getFragmentManager()); - } - } - - /** - * 在Activity或Fragment中的同名同参方法调用此方法 - */ - static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { - - OnPermission call = mContainer.get(requestCode); - - //根据请求码取出的对象为空,就直接返回不处理 - if (call == null) return; - - List succeedPermissions = PermissionUtils.getSucceedPermissions(permissions, grantResults); - List failPermissions = PermissionUtils.getFailPermissions(permissions, grantResults); - //如果请求成功的权限集合大小和请求的数组一样大时证明权限已经全部授予 - if (succeedPermissions.size() == permissions.length) { - //代表申请的所有的权限都授予了 - call.hasPermission(succeedPermissions); - }else { - //代表申请的权限中有不同意授予的,如果拒绝的时间过快证明是系统自动拒绝 - call.noPermission(failPermissions, System.currentTimeMillis() - requestTime < 200); - //证明还有一部分权限被成功授予,回调成功接口 - if (!succeedPermissions.isEmpty()) { - call.hasPermission(succeedPermissions); - } - } - - //权限回调结束后要删除集合中的对象,避免重复请求 - mContainer.remove(requestCode); - } -} +package com.hjq.permissions; + +import android.app.Activity; +import android.util.SparseArray; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +/** + * Created by HJQ on 2018-6-15. + */ +public final class XXPermissions { + + private final static SparseArray mContainer = new SparseArray<>(); + + private static long requestTime; + + private Activity mActivity; + private String[] mPermissions; + + /** + * 不能被外部实例化 + */ + private XXPermissions(Activity activity) { + this.mActivity = activity; + } + + /** + * 设置请求的对象 + */ + public static XXPermissions with(Activity activity) { + return new XXPermissions(activity); + } + + /** + * 设置权限组 + */ + public XXPermissions permission(String... permissions){ + this.mPermissions = permissions; + return this; + } + + /** + * 设置权限组 + */ + public XXPermissions permission(String[]... permissions){ + List permissionList = new ArrayList<>(); + for (String[] group : permissions) { + permissionList.addAll(Arrays.asList(group)); + } + this.mPermissions = permissionList.toArray(new String[permissionList.size() - 1]); + return this; + } + + /** + * 请求权限 + */ + public void request(OnPermission call) { + //如果没有指定请求的权限,就使用清单注册的权限进行请求 + if (mPermissions == null || mPermissions.length == 0) this.mPermissions = PermissionUtils.getPermissions(mActivity); + if (mPermissions == null || mPermissions.length == 0) throw new IllegalArgumentException("The requested permission cannot be empty"); + //使用isFinishing方法Activity在熄屏状态下会导致崩溃 + //if (mActivity == null || mActivity.isFinishing()) throw new IllegalArgumentException("Illegal Activity was passed in"); + if (mActivity == null) throw new IllegalArgumentException("The activity is empty"); + if (call == null) throw new IllegalArgumentException("The permission request callback interface must be implemented"); + + int requestCode; + + //请求码随机生成,避免随机产生之前的请求码,必须进行循环判断 + do { + //requestCode = new Random().nextInt(65535);//Studio编译的APK请求码必须小于65536 + requestCode = new Random().nextInt(255);//Eclipse编译的APK请求码必须小于256 + } while (mContainer.get(requestCode) != null); + + ArrayList failPermissions = PermissionUtils.getFailPermissions(mActivity, mPermissions); + + if (failPermissions.isEmpty()) { + //证明权限已经全部授予过 + call.hasPermission(Arrays.asList(mPermissions)); + } else { + //将当前的请求码和对象添加到集合中 + mContainer.put(requestCode, call); + //记录本次申请时间 + requestTime = System.currentTimeMillis(); + //检测权限有没有在清单文件中注册 + PermissionUtils.checkPermissions(mActivity, mPermissions); + //申请没有授予过的权限 + PermissionFragment.newInstant(failPermissions, requestCode).request(mActivity.getFragmentManager()); + } + } + + /** + * 在Activity或Fragment中的同名同参方法调用此方法 + */ + static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + + OnPermission call = mContainer.get(requestCode); + + //根据请求码取出的对象为空,就直接返回不处理 + if (call == null) return; + + List succeedPermissions = PermissionUtils.getSucceedPermissions(permissions, grantResults); + List failPermissions = PermissionUtils.getFailPermissions(permissions, grantResults); + //如果请求成功的权限集合大小和请求的数组一样大时证明权限已经全部授予 + if (succeedPermissions.size() == permissions.length) { + //代表申请的所有的权限都授予了 + call.hasPermission(succeedPermissions); + }else { + //代表申请的权限中有不同意授予的,如果拒绝的时间过快证明是系统自动拒绝 + call.noPermission(failPermissions, System.currentTimeMillis() - requestTime < 200); + //证明还有一部分权限被成功授予,回调成功接口 + if (!succeedPermissions.isEmpty()) { + call.hasPermission(succeedPermissions); + } + } + + //权限回调结束后要删除集合中的对象,避免重复请求 + mContainer.remove(requestCode); + } +}