├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── github
│ │ │ │ └── dfqin
│ │ │ │ └── permissiondemo
│ │ │ │ ├── ContactInfo.java
│ │ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── github
│ │ │ └── dfqin
│ │ │ └── permissiondemo
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── dfqin
│ │ └── permissiondemo
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── grantor
├── .gitignore
├── gradle.properties
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ └── values-v21
│ │ │ └── styles.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── dfqin
│ │ └── grantor
│ │ ├── PermissionListener.java
│ │ ├── PermissionsUtil.java
│ │ └── PermissionActivity.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── grant1.gif
├── grant2.gif
├── grant3.gif
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README.md
├── maven-push.gradle
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/grantor/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':grantor'
2 |
--------------------------------------------------------------------------------
/grant1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/grant1.gif
--------------------------------------------------------------------------------
/grant2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/grant2.gif
--------------------------------------------------------------------------------
/grant3.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/grant3.gif
--------------------------------------------------------------------------------
/grantor/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=Android TagGroup Library
2 | POM_ARTIFACT_ID=grantor
3 | POM_PACKAGING=aar
--------------------------------------------------------------------------------
/grantor/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Grantor
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | PermissionDemo
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dfqin/PermissionGrantor/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/grantor/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/grantor/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/test/java/com/github/dfqin/permissiondemo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.github.dfqin.permissiondemo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/grantor/src/main/java/com/github/dfqin/grantor/PermissionListener.java:
--------------------------------------------------------------------------------
1 | package com.github.dfqin.grantor;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | /**
6 | * Created by dfqin on 2017/1/20.
7 | */
8 |
9 | public interface PermissionListener {
10 |
11 | /**
12 | * 通过授权
13 | * @param permission
14 | */
15 | void permissionGranted(@NonNull String[] permission);
16 |
17 | /**
18 | * 拒绝授权
19 | * @param permission
20 | */
21 | void permissionDenied(@NonNull String[] permission);
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/github/dfqin/permissiondemo/ContactInfo.java:
--------------------------------------------------------------------------------
1 | package com.github.dfqin.permissiondemo;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * Created by dfqin on 17/2/7.
7 | */
8 |
9 | public class ContactInfo {
10 | /**
11 | * name
12 | */
13 | public String n = "";
14 |
15 | /**
16 | * phones
17 | */
18 | public List p;
19 |
20 | /**
21 | * email
22 | *
23 | */
24 | public String m = "";
25 |
26 | /**
27 | * company
28 | */
29 | public String o = "";
30 |
31 | /**
32 | * address
33 | */
34 | public String a = "";
35 | }
36 |
--------------------------------------------------------------------------------
/grantor/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/dfqin/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/grantor/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/dfqin/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/grantor/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply from: '../maven-push.gradle'
3 |
4 | android {
5 | compileSdkVersion 23
6 | buildToolsVersion "24.0.1"
7 |
8 | defaultConfig {
9 | minSdkVersion 14
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | compile fileTree(dir: 'libs', include: ['*.jar'])
27 | compile 'com.android.support:appcompat-v7:23.0.0'
28 | }
29 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/github/dfqin/permissiondemo/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.github.dfqin.permissiondemo;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.github.dfqin.permissiondemo", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "24.0.1"
6 | defaultConfig {
7 | applicationId "com.github.dfqin.permissiondemo"
8 | minSdkVersion 14
9 | targetSdkVersion 23
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(include: ['*.jar'], dir: 'libs')
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile project(':grantor')
28 | compile 'com.android.support:appcompat-v7:23.0.0'
29 | //compile 'com.github.dfqin:grantor:1.0.1'
30 | testCompile 'junit:junit:4.12'
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
19 | VERSION_NAME=2.5
20 | VERSION_CODE=9
21 | GROUP=com.github.dfqin
22 |
23 | POM_DESCRIPTION=Android Library to grant the permission
24 | POM_URL=https://github.com/dfqin/Grantor
25 | POM_SCM_URL=https://github.com/dfqin/Grantor
26 | POM_SCM_CONNECTION=scm:https://github.com/dfqin/Grantor.git
27 | POM_SCM_DEV_CONNECTION=scm:https://github.com/dfqin/Grantor.git
28 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
29 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
30 | POM_LICENCE_DIST=repo
31 | POM_DEVELOPER_ID=dfqin
32 | POM_DEVELOPER_NAME=Qin Dongfang
33 |
34 | SNAPSHOT_REPOSITORY_URL=https://oss.sonatype.org/content/repositories/snapshots
35 | RELEASE_REPOSITORY_URL=https://oss.sonatype.org/service/local/staging/deploy/maven2
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
20 |
21 |
27 |
28 |
34 |
35 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | ### update 2017-07-31
3 | fix bug on XiaoMi device
4 |
5 | ### update 2017-08-08
6 | update dialog style
7 |
8 | ### update 2017-08-29
9 | set minSdkVersion to 14
10 |
11 | ### update 2017-11-15
12 | 申请授权不依赖于Activity对象
13 |
14 | ### Grantor
15 | An Android permission grant util which is concise and easy to use. Normally you need to request permission in an Activity or Fragment and get the result by inheriting its method:
16 | ```
17 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
18 | @NonNull int[] grantResults) {
19 | /* callback - no nothing */
20 | }
21 | ```
22 | If you request permissions in other Class(for example in a widget), things will become complicated. Grantor handle permission in alone Activity and simplify the work, when user deny permission, by default it's can show a dialog to explain why you need the permission, of course you can config it not to show the explaining dialog.
23 | ### How to use
24 | * 1 add to module's dependencies.
25 | ```
26 | dependencies {
27 | compile 'com.github.dfqin:grantor:2.5'
28 | }
29 | ```
30 | * 2 use in your code.
31 | ```
32 | PermissionsUtil.requestPermission(Context context, PermissionListener listener, String[] permissions);
33 | ```
34 | * 3 some demo.
35 |
36 | ```
37 | private void requestCemera() {
38 | PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
39 | @Override
40 | public void permissionGranted(@NonNull String[] permissions) {
41 | Toast.makeText(MainActivity.this, "访问摄像头", Toast.LENGTH_LONG).show();
42 | }
43 |
44 | @Override
45 | public void permissionDenied(@NonNull String[] permissions) {
46 | Toast.makeText(MainActivity.this, "用户拒绝了访问摄像头", Toast.LENGTH_LONG).show();
47 | }
48 | }, Manifest.permission.CAMERA);
49 | }
50 |
51 |
52 | private void requestReadContact() {
53 | PermissionsUtil.TipInfo tip = new PermissionsUtil.TipInfo("注意:", "我就是想看下你的通讯录", "不让看", "打开权限");
54 | PermissionsUtil.requestPermission(this, new PermissionListener() {
55 | @Override
56 | public void permissionGranted(@NonNull String[] permissions) {
57 | JSONArray arr = null;
58 | try {
59 | arr = getContactInfo(MainActivity.this);
60 | if (arr.length() == 0) {
61 | Toast.makeText(MainActivity.this, "请确认通讯录不为空且有访问权限", Toast.LENGTH_LONG).show();
62 | } else {
63 | Toast.makeText(MainActivity.this, arr.toString(), Toast.LENGTH_LONG).show();
64 | }
65 |
66 | } catch (JSONException e) {
67 | e.printStackTrace();
68 | }
69 | }
70 |
71 | @Override
72 | public void permissionDenied(@NonNull String[] permissions) {
73 | Toast.makeText(MainActivity.this, "用户拒绝了读取通讯录权限", Toast.LENGTH_LONG).show();
74 | }
75 | }, new String[]{Manifest.permission.READ_CONTACTS}, true, tip);
76 | }
77 |
78 | private void requestSms() {
79 |
80 | PermissionsUtil.requestPermission(this, new PermissionListener() {
81 | @Override
82 | public void permissionGranted(@NonNull String[] permissions) {
83 | Toast.makeText(MainActivity.this, "访问消息", Toast.LENGTH_LONG).show();
84 | }
85 |
86 | @Override
87 | public void permissionDenied(@NonNull String[] permissions) {
88 | Toast.makeText(MainActivity.this, "用户拒绝了读取消息权限", Toast.LENGTH_LONG).show();
89 | }
90 | }, new String[]{Manifest.permission.READ_SMS}, false, null);
91 | }
92 |
93 | ```
94 | * 4 the demo image.
95 |
96 | 
97 |
98 |
99 | 
100 |
101 |
102 | 
103 |
104 | ### License
105 | [The MIT License (MIT)](http://opensource.org/licenses/MIT)
106 | Copyright (c) 2017, dfqin
107 |
--------------------------------------------------------------------------------
/maven-push.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Chris Banes
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | apply plugin: 'maven'
18 | apply plugin: 'signing'
19 |
20 | def isReleaseBuild() {
21 | return VERSION_NAME.contains("SNAPSHOT") == false
22 | }
23 |
24 | def getReleaseRepositoryUrl() {
25 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL
26 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
27 | }
28 |
29 | def getSnapshotRepositoryUrl() {
30 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL
31 | : "https://oss.sonatype.org/content/repositories/snapshots/"
32 | }
33 |
34 | def getRepositoryUsername() {
35 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
36 | }
37 |
38 | def getRepositoryPassword() {
39 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
40 | }
41 |
42 | afterEvaluate { project ->
43 | uploadArchives {
44 | repositories {
45 | mavenDeployer {
46 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
47 |
48 | pom.groupId = GROUP
49 | pom.artifactId = POM_ARTIFACT_ID
50 | pom.version = VERSION_NAME
51 |
52 | repository(url: getReleaseRepositoryUrl()) {
53 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
54 | }
55 | snapshotRepository(url: getSnapshotRepositoryUrl()) {
56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
57 | }
58 |
59 | pom.project {
60 | name POM_NAME
61 | packaging POM_PACKAGING
62 | description POM_DESCRIPTION
63 | url POM_URL
64 |
65 | scm {
66 | url POM_SCM_URL
67 | connection POM_SCM_CONNECTION
68 | developerConnection POM_SCM_DEV_CONNECTION
69 | }
70 |
71 | licenses {
72 | license {
73 | name POM_LICENCE_NAME
74 | url POM_LICENCE_URL
75 | distribution POM_LICENCE_DIST
76 | }
77 | }
78 |
79 | developers {
80 | developer {
81 | id POM_DEVELOPER_ID
82 | name POM_DEVELOPER_NAME
83 | }
84 | }
85 | }
86 | }
87 | }
88 | }
89 |
90 | signing {
91 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
92 | sign configurations.archives
93 | }
94 |
95 | task apklib(type: Zip){
96 | appendix = extension = 'apklib'
97 |
98 | from 'AndroidManifest.xml'
99 | into('res') {
100 | from 'res'
101 | }
102 | into('src') {
103 | from 'src'
104 | }
105 | }
106 |
107 | task androidJavadocs(type: Javadoc) {
108 | source = android.sourceSets.main.java.srcDirs
109 | classpath += project.files(android.getBootClasspath() .join(File.pathSeparator))
110 | }
111 |
112 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
113 | classifier = 'javadoc'
114 | from androidJavadocs.destinationDir
115 | }
116 |
117 | task androidSourcesJar(type: Jar) {
118 | classifier = 'sources'
119 | from android.sourceSets.main.java.srcDirs
120 | }
121 |
122 | artifacts {
123 | archives androidSourcesJar
124 | archives androidJavadocsJar
125 | archives apklib
126 | }
127 | }
--------------------------------------------------------------------------------
/grantor/src/main/java/com/github/dfqin/grantor/PermissionsUtil.java:
--------------------------------------------------------------------------------
1 | package com.github.dfqin.grantor;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.content.pm.PackageManager;
7 | import android.net.Uri;
8 | import android.os.Build;
9 | import android.provider.Settings;
10 | import android.support.annotation.NonNull;
11 | import android.support.annotation.Nullable;
12 | import android.support.v4.content.PermissionChecker;
13 | import android.util.Log;
14 |
15 | import java.io.Serializable;
16 | import java.util.HashMap;
17 |
18 | /**
19 | * Created by dfqin on 2017/1/20.
20 | */
21 |
22 | public class PermissionsUtil {
23 |
24 | public static final String TAG = "PermissionGrantor";
25 | private static HashMap listenerMap = new HashMap();
26 |
27 | /**
28 | * 申请授权,当用户拒绝时,会显示默认一个默认的Dialog提示用户
29 | * @param context
30 | * @param listener
31 | * @param permission 要申请的权限
32 | */
33 | public static void requestPermission(Context context, PermissionListener listener, String... permission) {
34 | requestPermission(context, listener, permission, true, null);
35 | }
36 |
37 | /**
38 | * 申请授权,当用户拒绝时,可以设置是否显示Dialog提示用户,也可以设置提示用户的文本内容
39 | * @param context
40 | * @param listener
41 | * @param permission 需要申请授权的权限
42 | * @param showTip 当用户拒绝授权时,是否显示提示
43 | * @param tip 当用户拒绝时要显示Dialog设置
44 | */
45 | public static void requestPermission(@NonNull Context context, @NonNull PermissionListener listener
46 | , @NonNull String[] permission, boolean showTip, @Nullable TipInfo tip) {
47 |
48 | if (listener == null) {
49 | Log.e(TAG, "listener is null");
50 | return;
51 | }
52 |
53 | if (PermissionsUtil.hasPermission(context, permission)) {
54 | listener.permissionGranted(permission);
55 | } else {
56 | if (Build.VERSION.SDK_INT < 23) {
57 | listener.permissionDenied(permission);
58 | } else {
59 | String key = String.valueOf(System.currentTimeMillis());
60 | listenerMap.put(key, listener);
61 | Intent intent = new Intent(context, PermissionActivity.class);
62 | intent.putExtra("permission", permission);
63 | intent.putExtra("key", key);
64 | intent.putExtra("showTip", showTip);
65 | intent.putExtra("tip", tip);
66 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
67 |
68 | context.startActivity(intent);
69 | }
70 | }
71 | }
72 |
73 |
74 | /**
75 | * 判断权限是否授权
76 | * @param context
77 | * @param permissions
78 | * @return
79 | */
80 | public static boolean hasPermission(@NonNull Context context, @NonNull String... permissions) {
81 |
82 | if (permissions.length == 0) {
83 | return false;
84 | }
85 |
86 | for (String per : permissions ) {
87 | int result = PermissionChecker.checkSelfPermission(context, per);
88 | if ( result != PermissionChecker.PERMISSION_GRANTED) {
89 | return false;
90 | }
91 | }
92 |
93 | return true;
94 | }
95 |
96 | /**
97 | * 判断一组授权结果是否为授权通过
98 | * @param grantResult
99 | * @return
100 | */
101 | public static boolean isGranted(@NonNull int... grantResult) {
102 |
103 | if (grantResult.length == 0) {
104 | return false;
105 | }
106 |
107 | for (int result : grantResult) {
108 | if (result != PackageManager.PERMISSION_GRANTED) {
109 | return false;
110 | }
111 | }
112 | return true;
113 | }
114 |
115 | /**
116 | * 跳转到当前应用对应的设置页面
117 | * @param context
118 | */
119 | public static void gotoSetting(@NonNull Context context) {
120 | Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
121 | intent.setData(Uri.parse("package:" + context.getPackageName()));
122 | context.startActivity(intent);
123 | }
124 |
125 | /**
126 | *
127 | * @param key
128 | * @return
129 | */
130 | static PermissionListener fetchListener(String key) {
131 | return listenerMap.remove(key);
132 | }
133 |
134 |
135 | public static class TipInfo implements Serializable {
136 |
137 | private static final long serialVersionUID = 1L;
138 |
139 | String title;
140 | String content;
141 | String cancel; //取消按钮文本
142 | String ensure; //确定按钮文本
143 |
144 | public TipInfo ( @Nullable String title, @Nullable String content, @Nullable String cancel, @Nullable String ensure) {
145 | this.title = title;
146 | this.content = content;
147 | this.cancel = cancel;
148 | this.ensure = ensure;
149 | }
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/grantor/src/main/java/com/github/dfqin/grantor/PermissionActivity.java:
--------------------------------------------------------------------------------
1 | package com.github.dfqin.grantor;
2 |
3 | /**
4 | * Created by dfqin on 2017/1/22.
5 | */
6 |
7 | import android.app.Activity;
8 | import android.content.DialogInterface;
9 | import android.os.Bundle;
10 | import android.support.annotation.NonNull;
11 | import android.support.annotation.Nullable;
12 | import android.support.v4.app.ActivityCompat;
13 | import android.support.v7.app.AlertDialog;
14 | import android.support.v7.app.AppCompatActivity;
15 | import android.text.TextUtils;
16 |
17 | import java.io.Serializable;
18 |
19 | public class PermissionActivity extends AppCompatActivity {
20 |
21 |
22 | private static final int PERMISSION_REQUEST_CODE = 64;
23 | private boolean isRequireCheck;
24 |
25 | private String[] permission;
26 | private String key;
27 | private boolean showTip;
28 | private PermissionsUtil.TipInfo tipInfo;
29 |
30 | private final String defaultTitle = "帮助";
31 | private final String defaultContent = "当前应用缺少必要权限。\n \n 请点击 \"设置\"-\"权限\"-打开所需权限。";
32 | private final String defaultCancel = "取消";
33 | private final String defaultEnsure = "设置";
34 |
35 | @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | if (getIntent() == null || !getIntent().hasExtra("permission")) {
38 | finish();
39 | return;
40 | }
41 |
42 | isRequireCheck = true;
43 | permission = getIntent().getStringArrayExtra("permission");
44 | key = getIntent().getStringExtra("key");
45 | showTip = getIntent().getBooleanExtra("showTip", true);
46 | Serializable ser = getIntent().getSerializableExtra("tip");
47 |
48 | if (ser == null) {
49 | tipInfo = new PermissionsUtil.TipInfo(defaultTitle, defaultContent, defaultCancel, defaultEnsure);
50 | } else {
51 | tipInfo = (PermissionsUtil.TipInfo)ser;
52 | }
53 |
54 | }
55 |
56 | @Override protected void onResume() {
57 | super.onResume();
58 | if (isRequireCheck) {
59 | if (PermissionsUtil.hasPermission(this, permission)) {
60 | permissionsGranted();
61 | } else {
62 | requestPermissions(permission); // 请求权限,回调时会触发onResume
63 | isRequireCheck = false;
64 | }
65 | } else {
66 | isRequireCheck = true;
67 | }
68 | }
69 |
70 | // 请求权限兼容低版本
71 | private void requestPermissions(String[] permission) {
72 | ActivityCompat.requestPermissions(this, permission, PERMISSION_REQUEST_CODE);
73 | }
74 |
75 |
76 | /**
77 | * 用户权限处理,
78 | * 如果全部获取, 则直接过.
79 | * 如果权限缺失, 则提示Dialog.
80 | *
81 | * @param requestCode 请求码
82 | * @param permissions 权限
83 | * @param grantResults 结果
84 | */
85 | @Override
86 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
87 |
88 | //部分厂商手机系统返回授权成功时,厂商可以拒绝权限,所以要用PermissionChecker二次判断
89 | if (requestCode == PERMISSION_REQUEST_CODE && PermissionsUtil.isGranted(grantResults)
90 | && PermissionsUtil.hasPermission(this, permissions)) {
91 | permissionsGranted();
92 | } else if (showTip){
93 | showMissingPermissionDialog();
94 | } else { //不需要提示用户
95 | permissionsDenied();
96 | }
97 | }
98 |
99 | // 显示缺失权限提示
100 | private void showMissingPermissionDialog() {
101 |
102 | AlertDialog.Builder builder = new AlertDialog.Builder(PermissionActivity.this);
103 |
104 | builder.setTitle(TextUtils.isEmpty(tipInfo.title) ? defaultTitle : tipInfo.title);
105 | builder.setMessage(TextUtils.isEmpty(tipInfo.content) ? defaultContent : tipInfo.content);
106 |
107 | builder.setNegativeButton(TextUtils.isEmpty(tipInfo.cancel) ? defaultCancel : tipInfo.cancel, new DialogInterface.OnClickListener(){
108 | @Override public void onClick(DialogInterface dialog, int which) {
109 | permissionsDenied();
110 | }
111 | });
112 |
113 | builder.setPositiveButton(TextUtils.isEmpty(tipInfo.ensure) ? defaultEnsure : tipInfo.ensure, new DialogInterface.OnClickListener() {
114 | @Override public void onClick(DialogInterface dialog, int which) {
115 | PermissionsUtil.gotoSetting(PermissionActivity.this);
116 | }
117 | });
118 |
119 | builder.setCancelable(false);
120 | builder.show();
121 | }
122 |
123 | private void permissionsDenied() {
124 | PermissionListener listener = PermissionsUtil.fetchListener(key);
125 | if (listener != null) {
126 | listener.permissionDenied(permission);
127 | }
128 | finish();
129 | }
130 |
131 | // 全部权限均已获取
132 | private void permissionsGranted() {
133 | PermissionListener listener = PermissionsUtil.fetchListener(key);
134 | if (listener != null) {
135 | listener.permissionGranted(permission);
136 | }
137 | finish();
138 | }
139 |
140 | protected void onDestroy() {
141 | PermissionsUtil.fetchListener(key);
142 | super.onDestroy();
143 | }
144 |
145 | }
146 |
147 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/github/dfqin/permissiondemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.github.dfqin.permissiondemo;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.ContentUris;
6 | import android.content.ContentValues;
7 | import android.database.Cursor;
8 | import android.net.Uri;
9 | import android.provider.ContactsContract;
10 | import android.support.annotation.NonNull;
11 | import android.support.v7.app.AppCompatActivity;
12 | import android.os.Bundle;
13 | import android.text.TextUtils;
14 | import android.view.View;
15 | import android.widget.Toast;
16 |
17 | import com.github.dfqin.grantor.PermissionListener;
18 | import com.github.dfqin.grantor.PermissionsUtil;
19 |
20 | import org.json.JSONArray;
21 | import org.json.JSONException;
22 | import org.json.JSONObject;
23 | import android.provider.ContactsContract.Data;
24 |
25 | import java.util.ArrayList;
26 |
27 | public class MainActivity extends AppCompatActivity {
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_main);
33 |
34 | findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
35 | @Override
36 | public void onClick(View view) {
37 | requestCemera();
38 | }
39 | });
40 |
41 | findViewById(R.id.btn_read_contact).setOnClickListener(new View.OnClickListener() {
42 | @Override
43 | public void onClick(View view) {
44 | requestReadContact();
45 | }
46 | });
47 |
48 | findViewById(R.id.btn_sms).setOnClickListener(new View.OnClickListener() {
49 | @Override
50 | public void onClick(View v) {
51 | requestSms();
52 | }
53 | });
54 |
55 | findViewById(R.id.btn_write_contact).setOnClickListener(new View.OnClickListener() {
56 | @Override
57 | public void onClick(View v) {
58 | requestWriteContact();
59 | }
60 | });
61 | }
62 |
63 |
64 | private void requestCemera() {
65 | PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
66 | @Override
67 | public void permissionGranted(@NonNull String[] permissions) {
68 | Toast.makeText(MainActivity.this, "访问摄像头", Toast.LENGTH_LONG).show();
69 | }
70 |
71 | @Override
72 | public void permissionDenied(@NonNull String[] permissions) {
73 | Toast.makeText(MainActivity.this, "用户拒绝了访问摄像头", Toast.LENGTH_LONG).show();
74 | }
75 | }, Manifest.permission.CAMERA);
76 | }
77 |
78 |
79 | private void requestReadContact() {
80 | PermissionsUtil.TipInfo tip = new PermissionsUtil.TipInfo("注意:", "我就是想看下你的通讯录", "不让看", "打开权限");
81 | PermissionsUtil.requestPermission(this, new PermissionListener() {
82 | @Override
83 | public void permissionGranted(@NonNull String[] permissions) {
84 | JSONArray arr = null;
85 | try {
86 | arr = getContactInfo(MainActivity.this);
87 | if (arr.length() == 0) {
88 | Toast.makeText(MainActivity.this, "请确认通讯录不为空且有访问权限", Toast.LENGTH_LONG).show();
89 | } else {
90 | Toast.makeText(MainActivity.this, arr.toString(), Toast.LENGTH_LONG).show();
91 | }
92 |
93 | } catch (JSONException e) {
94 | e.printStackTrace();
95 | }
96 | }
97 |
98 | @Override
99 | public void permissionDenied(@NonNull String[] permissions) {
100 | Toast.makeText(MainActivity.this, "用户拒绝了读取通讯录权限", Toast.LENGTH_LONG).show();
101 | }
102 | }, new String[]{Manifest.permission.READ_CONTACTS}, true, tip);
103 | }
104 |
105 | private void requestSms() {
106 |
107 | PermissionsUtil.requestPermission(this, new PermissionListener() {
108 | @Override
109 | public void permissionGranted(@NonNull String[] permissions) {
110 | Toast.makeText(MainActivity.this, "访问消息", Toast.LENGTH_LONG).show();
111 | }
112 |
113 | @Override
114 | public void permissionDenied(@NonNull String[] permissions) {
115 | Toast.makeText(MainActivity.this, "用户拒绝了读取消息权限", Toast.LENGTH_LONG).show();
116 | }
117 | }, new String[]{Manifest.permission.READ_SMS}, false, null);
118 | }
119 |
120 |
121 | private void requestWriteContact() {
122 | PermissionsUtil.requestPermission(this, new PermissionListener() {
123 | @Override
124 | public void permissionGranted(@NonNull String[] permissions) {
125 | if (addContact("dfqin", "17717018888")) {
126 | Toast.makeText(MainActivity.this, "成功添加联系人", Toast.LENGTH_LONG).show();
127 | } else {
128 | Toast.makeText(MainActivity.this, "添加联系人失败", Toast.LENGTH_LONG).show();
129 | }
130 | }
131 |
132 | @Override
133 | public void permissionDenied(@NonNull String[] permissions) {
134 | Toast.makeText(MainActivity.this, "用户拒绝了写通讯录", Toast.LENGTH_LONG).show();
135 | }
136 | }, Manifest.permission.WRITE_CONTACTS);
137 | }
138 |
139 |
140 | // 一个添加联系人信息的例子
141 | private boolean addContact(String name, String phoneNumber) {
142 | // 创建一个空的ContentValues
143 | ContentValues values = new ContentValues();
144 |
145 | Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
146 | if (rawContactUri == null) {
147 | return false;
148 | }
149 |
150 | long rawContactId = ContentUris.parseId(rawContactUri);
151 | values.clear();
152 |
153 | values.put(Data.RAW_CONTACT_ID, rawContactId);
154 | // 内容类型
155 | values.put(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
156 | // 联系人名字
157 | values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
158 | // 向联系人URI添加联系人名字
159 | getContentResolver().insert(Data.CONTENT_URI, values);
160 | values.clear();
161 |
162 | values.put(Data.RAW_CONTACT_ID, rawContactId);
163 | values.put(Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
164 | // 联系人的电话号码
165 | values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
166 | // 电话类型
167 | values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
168 | // 向联系人电话号码URI添加电话号码
169 | getContentResolver().insert(Data.CONTENT_URI, values);
170 | values.clear();
171 |
172 | values.put(Data.RAW_CONTACT_ID, rawContactId);
173 | values.put(Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
174 | // 联系人的Email地址
175 | values.put(ContactsContract.CommonDataKinds.Email.DATA, "test@163.com");
176 | // 电子邮件的类型
177 | values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK);
178 | // 向联系人Email URI添加Email数据
179 | getContentResolver().insert(Data.CONTENT_URI, values);
180 |
181 | return true;
182 | }
183 |
184 | private JSONArray getContactInfo(Activity activity) throws JSONException {
185 | // 获得通讯录信息 ,URI是ContactsContract.Contacts.CONTENT_URI
186 | ArrayList contacts = new ArrayList<>();
187 | String mimetype = "";
188 | int oldrid = -1;
189 | int contactId = -1;
190 | Cursor cursor = activity.getContentResolver().query(ContactsContract.Data.CONTENT_URI,null
191 | , null, null, ContactsContract.Data.RAW_CONTACT_ID);
192 | int numm=0;
193 | ContactInfo contact = null;
194 |
195 | if (cursor != null) {
196 | while (cursor.moveToNext()) {
197 | int index = cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
198 | if (index < 0) {
199 | cursor.close();
200 | return null;
201 | }
202 | contactId = cursor.getInt(index);
203 | if (oldrid != contactId) {
204 | contact = new ContactInfo();
205 | contacts.add(contact);
206 | numm++;
207 | oldrid = contactId;
208 | }
209 | // 取得mimetype类型
210 | mimetype = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
211 |
212 | /************* 获取通讯录中名字 **************/
213 | if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mimetype)) {
214 | StringBuilder name = new StringBuilder();
215 | String firstName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
216 | if (!TextUtils.isEmpty(firstName)) {
217 | name.append(firstName);
218 | }
219 |
220 | String middleName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
221 | if (!TextUtils.isEmpty(middleName)) {
222 | name.append(middleName);
223 | }
224 |
225 | String lastname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
226 | if (!TextUtils.isEmpty(lastname)) {
227 | name.append(lastname);
228 | }
229 |
230 | contact.n = name.toString();
231 | }
232 |
233 | /***************** 获取电话 ********************/
234 | if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mimetype)) {
235 | if (contact.p == null) {
236 | contact.p = new ArrayList<>();
237 | }
238 | String mobile = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
239 | if (!TextUtils.isEmpty(mobile)) {
240 | contact.p.add(mobile);
241 | }
242 | }
243 |
244 | /******************** 获取第一个邮件 *******************/
245 | if (ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE.equals(mimetype)) {
246 | if (!TextUtils.isEmpty(contact.m)) {
247 | continue;
248 | }
249 | String email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
250 | contact.m = email == null ? "" : email;
251 | }
252 |
253 | /******************** 获取公司信息 *******************/
254 | if (ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE.equals(mimetype)) {
255 | // 取出组织类型
256 | int orgType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE));
257 | // 单位
258 | if (orgType == ContactsContract.CommonDataKinds.Organization.TYPE_CUSTOM) {
259 | String company = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
260 | contact.o = company == null ? "" : company;
261 | }
262 | }
263 |
264 | /******************** 获取地址 *******************/
265 | if (ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE.equals(mimetype)) {
266 | if (!TextUtils.isEmpty(contact.a)) {
267 | continue;
268 | }
269 | // 取出类型
270 | int postalType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
271 | // 住宅通讯地址
272 | if (postalType == ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME) {
273 | String homeStreet = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
274 | contact.a = homeStreet == null ? "" : homeStreet;
275 | }
276 | // 单位通讯地址
277 | if (postalType == ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK) {
278 | String street = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
279 | contact.a = street == null ? "" : street;
280 | }
281 | // 其他通讯地址
282 | if (postalType == ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER) {
283 | String otherStreet = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
284 | contact.a = otherStreet == null ? "" : otherStreet;
285 | }
286 | }
287 | }
288 | }
289 | cursor.close();
290 | JSONArray arr = new JSONArray();
291 | for (ContactInfo con : contacts) {
292 |
293 | StringBuilder sb = new StringBuilder();
294 | sb.append(con.n);
295 | if (con.p != null && con.p.size() > 0) {
296 | sb.append(con.p.get(0));
297 | }
298 | arr.put(sb.toString());
299 | }
300 | return arr;
301 | }
302 |
303 | }
304 |
--------------------------------------------------------------------------------