Android6.0权限申请工具类

Android6.0以上,有部分权限是需要申请的。共9组,只要一个权限申请成功默认这一组的权限也申请成功,看下图:

权限申请工具类如下:

  1 package com.example.android_lianshou_as.utils;
  2
  3 import android.Manifest;
  4 import android.app.Activity;
  5 import android.content.DialogInterface;
  6 import android.content.Intent;
  7 import android.content.pm.PackageManager;
  8 import android.net.Uri;
  9 import android.provider.Settings;
 10 import android.support.annotation.NonNull;
 11 import android.support.v4.app.ActivityCompat;
 12 import android.support.v7.app.AlertDialog;
 13 import android.util.Log;
 14 import android.widget.Toast;
 15
 16 import com.example.android_lianshou_as.R;
 17
 18 import java.util.ArrayList;
 19 import java.util.HashMap;
 20 import java.util.List;
 21 import java.util.Map;
 22
 23 /**
 24  * 申请权限工具类代码
 25  */
 26 public class PermissionUtils {
 27
 28     private static final String TAG = PermissionUtils.class.getSimpleName();
 29     public static final int CODE_RECORD_AUDIO = 0;
 30     public static final int CODE_GET_ACCOUNTS = 1;
 31     public static final int CODE_READ_PHONE_STATE = 2;
 32     public static final int CODE_CALL_PHONE = 3;
 33     public static final int CODE_CAMERA = 4;
 34     public static final int CODE_ACCESS_FINE_LOCATION = 5;
 35     public static final int CODE_ACCESS_COARSE_LOCATION = 6;
 36     public static final int CODE_READ_EXTERNAL_STORAGE = 7;
 37     public static final int CODE_WRITE_EXTERNAL_STORAGE = 8;
 38     public static final int CODE_MULTI_PERMISSION = 100;
 39
 40     public static final String PERMISSION_RECORD_AUDIO = Manifest.permission.RECORD_AUDIO;
 41     public static final String PERMISSION_GET_ACCOUNTS = Manifest.permission.GET_ACCOUNTS;
 42     public static final String PERMISSION_READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE;
 43     public static final String PERMISSION_CALL_PHONE = Manifest.permission.CALL_PHONE;
 44     public static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
 45     public static final String PERMISSION_ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
 46     public static final String PERMISSION_ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
 47     public static final String PERMISSION_READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;
 48     public static final String PERMISSION_WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
 49
 50     private static final String[] requestPermissions = {
 51             PERMISSION_RECORD_AUDIO,
 52             PERMISSION_GET_ACCOUNTS,
 53             PERMISSION_READ_PHONE_STATE,
 54             PERMISSION_CALL_PHONE,
 55             PERMISSION_CAMERA,
 56             PERMISSION_ACCESS_FINE_LOCATION,
 57             PERMISSION_ACCESS_COARSE_LOCATION,
 58             PERMISSION_READ_EXTERNAL_STORAGE,
 59             PERMISSION_WRITE_EXTERNAL_STORAGE
 60     };
 61
 62     interface PermissionGrant {
 63         void onPermissionGranted(int requestCode);
 64     }
 65
 66     /**
 67      * Requests permission.
 68      *
 69      * @param activity
 70      * @param requestCode request code, e.g. if you need request CAMERA permission,parameters is PermissionUtils.CODE_CAMERA
 71      */
 72     public static void requestPermission(final Activity activity, final int requestCode, PermissionGrant permissionGrant) {
 73         if (activity == null) {
 74             return;
 75         }
 76
 77         Log.i(TAG, "requestPermission requestCode:" + requestCode);
 78         if (requestCode < 0 || requestCode >= requestPermissions.length) {
 79             Log.w(TAG, "requestPermission illegal requestCode:" + requestCode);
 80             return;
 81         }
 82
 83         final String requestPermission = requestPermissions[requestCode];
 84
 85         //如果是6.0以下的手机,ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED,
 86         // 但是,如果用户关闭了你申请的权限,ActivityCompat.checkSelfPermission(),会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null),
 87         // 你可以使用try{}catch(){},处理异常,也可以在这个地方,低于23就什么都不做,
 88         // 个人建议try{}catch(){}单独处理,提示用户开启权限。
 89 //        if (Build.VERSION.SDK_INT < 23) {
 90 //            return;
 91 //        }
 92
 93         int checkSelfPermission;
 94         try {
 95             checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
 96         } catch (RuntimeException e) {
 97             Toast.makeText(activity, "please open this permission", Toast.LENGTH_SHORT)
 98                     .show();
 99             Log.e(TAG, "RuntimeException:" + e.getMessage());
100             return;
101         }
102
103         if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
104             Log.i(TAG, "ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED");
105
106
107             if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
108                 Log.i(TAG, "requestPermission shouldShowRequestPermissionRationale");
109                 shouldShowRationale(activity, requestCode, requestPermission);
110
111             } else {
112                 Log.d(TAG, "requestCameraPermission else");
113                 ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);
114             }
115
116         } else {
117             Log.d(TAG, "ActivityCompat.checkSelfPermission ==== PackageManager.PERMISSION_GRANTED");
118             Toast.makeText(activity, "opened:" + requestPermissions[requestCode], Toast.LENGTH_SHORT).show();
119             permissionGrant.onPermissionGranted(requestCode);
120         }
121     }
122
123     private static void requestMultiResult(Activity activity, String[] permissions, int[] grantResults, PermissionGrant permissionGrant) {
124
125         if (activity == null) {
126             return;
127         }
128
129         //TODO
130         Log.d(TAG, "onRequestPermissionsResult permissions length:" + permissions.length);
131         Map<String, Integer> perms = new HashMap<>();
132
133         ArrayList<String> notGranted = new ArrayList<>();
134         for (int i = 0; i < permissions.length; i++) {
135             Log.d(TAG, "permissions: [i]:" + i + ", permissions[i]" + permissions[i] + ",grantResults[i]:" + grantResults[i]);
136             perms.put(permissions[i], grantResults[i]);
137             if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
138                 notGranted.add(permissions[i]);
139             }
140         }
141
142         if (notGranted.size() == 0) {
143             Toast.makeText(activity, "all permission success" + notGranted, Toast.LENGTH_SHORT)
144                     .show();
145             permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION);
146         } else {
147             openSettingActivity(activity, "those permission need granted!");
148         }
149
150     }
151
152
153     /**
154      * 一次申请多个权限
155      */
156     public static void requestMultiPermissions(final Activity activity, PermissionGrant grant) {
157
158         final List<String> permissionsList = getNoGrantedPermission(activity, false);
159         final List<String> shouldRationalePermissionsList = getNoGrantedPermission(activity, true);
160
161         //TODO checkSelfPermission
162         if (permissionsList == null || shouldRationalePermissionsList == null) {
163             return;
164         }
165         Log.d(TAG, "requestMultiPermissions permissionsList:" + permissionsList.size() + ",shouldRationalePermissionsList:" + shouldRationalePermissionsList.size());
166
167         if (permissionsList.size() > 0) {
168             ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]),
169                     CODE_MULTI_PERMISSION);
170             Log.d(TAG, "showMessageOKCancel requestPermissions");
171
172         } else if (shouldRationalePermissionsList.size() > 0) {
173             showMessageOKCancel(activity, "should open those permission",
174                     new DialogInterface.OnClickListener() {
175                         @Override
176                         public void onClick(DialogInterface dialog, int which) {
177                             ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),
178                                     CODE_MULTI_PERMISSION);
179                             Log.d(TAG, "showMessageOKCancel requestPermissions");
180                         }
181                     });
182         } else {
183             grant.onPermissionGranted(CODE_MULTI_PERMISSION);
184         }
185
186     }
187
188
189     private static void shouldShowRationale(final Activity activity, final int requestCode, final String requestPermission) {
190         //TODO
191         String[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);
192         showMessageOKCancel(activity, "Rationale: " + permissionsHint[requestCode], new DialogInterface.OnClickListener() {
193             @Override
194             public void onClick(DialogInterface dialog, int which) {
195                 ActivityCompat.requestPermissions(activity,
196                         new String[]{requestPermission},
197                         requestCode);
198                 Log.d(TAG, "showMessageOKCancel requestPermissions:" + requestPermission);
199             }
200         });
201     }
202
203     private static void showMessageOKCancel(final Activity context, String message, DialogInterface.OnClickListener okListener) {
204         new AlertDialog.Builder(context)
205                 .setMessage(message)
206                 .setPositiveButton("OK", okListener)
207                 .setNegativeButton("Cancel", null)
208                 .create()
209                 .show();
210
211     }
212
213     /**
214      * @param activity
215      * @param requestCode  Need consistent with requestPermission
216      * @param permissions
217      * @param grantResults
218      */
219     public static void requestPermissionsResult(final Activity activity, final int requestCode, @NonNull String[] permissions,
220                                                 @NonNull int[] grantResults, PermissionGrant permissionGrant) {
221
222         if (activity == null) {
223             return;
224         }
225         Log.d(TAG, "requestPermissionsResult requestCode:" + requestCode);
226
227         if (requestCode == CODE_MULTI_PERMISSION) {
228             requestMultiResult(activity, permissions, grantResults, permissionGrant);
229             return;
230         }
231
232         if (requestCode < 0 || requestCode >= requestPermissions.length) {
233             Log.w(TAG, "requestPermissionsResult illegal requestCode:" + requestCode);
234             Toast.makeText(activity, "illegal requestCode:" + requestCode, Toast.LENGTH_SHORT).show();
235             return;
236         }
237
238         Log.i(TAG, "onRequestPermissionsResult requestCode:" + requestCode + ",permissions:" + permissions.toString()
239                 + ",grantResults:" + grantResults.toString() + ",length:" + grantResults.length);
240
241         if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
242             Log.i(TAG, "onRequestPermissionsResult PERMISSION_GRANTED");
243             //TODO success, do something, can use callback
244             permissionGrant.onPermissionGranted(requestCode);
245
246         } else {
247             //TODO hint user this permission function
248             Log.i(TAG, "onRequestPermissionsResult PERMISSION NOT GRANTED");
249             //TODO
250             String[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);
251             openSettingActivity(activity, "Result" + permissionsHint[requestCode]);
252         }
253
254     }
255
256     private static void openSettingActivity(final Activity activity, String message) {
257
258         showMessageOKCancel(activity, message, new DialogInterface.OnClickListener() {
259             @Override
260             public void onClick(DialogInterface dialog, int which) {
261                 Intent intent = new Intent();
262                 intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
263                 Log.d(TAG, "getPackageName(): " + activity.getPackageName());
264                 Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
265                 intent.setData(uri);
266                 activity.startActivity(intent);
267             }
268         });
269     }
270
271
272     /**
273      * @param activity
274      * @param isShouldRationale true: return no granted and shouldShowRequestPermissionRationale permissions, false:return no granted and !shouldShowRequestPermissionRationale
275      * @return
276      */
277     public static ArrayList<String> getNoGrantedPermission(Activity activity, boolean isShouldRationale) {
278
279         ArrayList<String> permissions = new ArrayList<>();
280
281         for (int i = 0; i < requestPermissions.length; i++) {
282             String requestPermission = requestPermissions[i];
283
284
285             //TODO checkSelfPermission
286             int checkSelfPermission = -1;
287             try {
288                 checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
289             } catch (RuntimeException e) {
290                 Toast.makeText(activity, "please open those permission", Toast.LENGTH_SHORT)
291                         .show();
292                 Log.e(TAG, "RuntimeException:" + e.getMessage());
293                 return null;
294             }
295
296             if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
297                 Log.i(TAG, "getNoGrantedPermission ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED:" + requestPermission);
298
299                 if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
300                     Log.d(TAG, "shouldShowRequestPermissionRationale if");
301                     if (isShouldRationale) {
302                         permissions.add(requestPermission);
303                     }
304
305                 } else {
306
307                     if (!isShouldRationale) {
308                         permissions.add(requestPermission);
309                     }
310                     Log.d(TAG, "shouldShowRequestPermissionRationale else");
311                 }
312
313             }
314         }
315
316         return permissions;
317     }
318
319 }  

资源文件:

 1 <string-array name="permissions">
 2         <item>@string/permission_recode_audio_hint</item>
 3         <item>@string/permission_get_accounts_hint</item>
 4         <item>@string/permission_read_phone_hint</item>
 5         <item>@string/permission_call_phone_hint</item>
 6         <item>@string/permission_camera_hint</item>
 7         <item>@string/permission_access_fine_location_hint</item>
 8         <item>@string/permission_access_coarse_location_hint</item>
 9         <item>@string/permission_read_external_hint</item>
10         <item>@string/permission_white_external_hint</item>
11     </string-array>
12     <string name="permission_get_accounts_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_GET_ACCOUNTS</string>
13     <string name="permission_read_phone_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_READ_PHONE_STATE</string>
14     <string name="permission_call_phone_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_CALL_PHONE</string>
15     <string name="permission_camera_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_CAMERA</string>
16     <string name="permission_access_fine_location_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_ACCESS_FINE_LOCATION</string>
17     <string name="permission_access_coarse_location_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_ACCESS_COARSE_LOCATION</string>
18     <string name="permission_read_external_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_READ_EXTERNAL_STORAGE</string>
19     <string name="permission_white_external_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_WRITE_EXTERNAL_STORAGE</string>
20     <string name="permission_recode_audio_hint">没有此权限,无法开启这个功能,请开启权限。PERMISSION_RECORD_AUDIO</string>  

activity调用:

实现activitycompat.onRequestPermissionResultCallback重写其中方法,其次在需要申请的位置调用permissionUtils.requestPermission();

1 @Override
2   public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
3                                          @NonNull int[] grantResults) {
4       PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
5   } 
时间: 2024-10-04 13:27:25

Android6.0权限申请工具类的相关文章

android6.0权限管理工具EasyPermissionUtil

前言 android6.0開始,权限的申请发生了改变,申请变的动态化,也就是执行时权限,和iOS相仿,动态化的意思是指,在每次使用须要危急权限的方法的时候.须要检查程序是否获得了该权限的许可.动态化的权限申请能够让用户更加清晰的知道程序须要什么权限.以及程序中哪些地方的操作须要涉及用户安全. 不再是只在程序安装的时候,一次性把所须要的普通的.危急级别的权限一次性列出来.然后展示给用户. 当project项目的target Sdk为23时,因为考虑到用户假设没有进行权限的动态检查,那么在执行到须要

Android6.0权限系统

Android6.0权限系统 Android权限系统是一个非常重要的安全问题,因为它只有在安装时会询问一次.一旦软件本安装之后,应用程序可以在用户毫不知情的情况下使用这些权限来获取所有的内容. 很多坏蛋会通过这个安全缺陷来收集用户的个人信息并使用它们来做坏事的情况就不足为奇了. Android团队也意识到了这个问题.在经过了7年后,权限系统终于被重新设置了.从Anroid 6.0(API Level 23)开始,应用程序在安装时不会被授予任何权限,取而代之的是在运行时应用回去请求用户授予对应的权

Android 6.0权限申请

 一.6.0发布权限变化 1.Android需要手动加入权限申请原因: 1)权限分为了两类:一类是Normal Permissions,这类权限一般不涉及用户隐私,是不需要用户进行授权的,比如手机震动.访问网络等:另一类是Dangerous Permission,一般是涉及到用户隐私的,需要用户进行授权,比如读取sdcard.访问通讯录等. Normal Permissions如下 ACCESS_LOCATION_EXTRA_COMMANDS ACCESS_NETWORK_STATE ACCES

权限申请帮助类(百度定位)

package com.example.mycitylocation; import android.Manifest;import android.app.Activity;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.provider.Setti

[Baidu Map]百度地图 JAVASCRIPT API V2.0 大众版 工具类

关键代码: /* *@description 百度地图 JAVASCRIPT API V2.0 大众版 工具类 *@author YanZhiwei *@see http://developer.baidu.com/map/reference/index.php *@email [email protected] */ (function () { map = {}; infoWindow = {}; BmapUtils = { CONSTANT: { DYNAMIC_CITY: "上海&quo

1.Android6.0运行时权限简介_2.Android6.0权限适配之WRITE_EXTERNAL_STORAGE(SD卡写入)3_.Android 6.0 运行时权限理解

Android6.0运行时权限简介:http://unclechen.github.io/2016/03/05/Android6.0%E8%BF%90%E8%A1%8C%E6%97%B6%E6%9D%83%E9%99%90%E7%AE%80%E4%BB%8B/ Android6.0权限适配之WRITE_EXTERNAL_STORAGE(SD卡写入):https://blog.csdn.net/xiechengfa/article/details/52699233 Android 6.0 运行时权

Android拍照,相册选择图片以及Android6.0权限管理

概述 在android开发过程中,拍照或者从相册中选择图片是很常见的功能.下面要说得这个案例比较简单,用户点击按钮选择拍照或者打开相册选择图片,然后将选中的图片显示在手机上.android6.0后,推出了动态权限管理.以往我们将涉及到的权限全部写在清单文件中,只要用户安装了该程序,程序在运行过程中都会获得相应权限.android6.0后,对于一些特别敏感的权限,开发者必须在程序中进行声明.拍照和从相册选择图片都是涉及到用户隐私的敏感权限,必须在程序中进行声明. 大概的流程 创建布局文件,这里不多

Android6.0权限管理以及使用权限该注意的地方

Android 6.0 Marshmallow首次增加了执行时权限管理,这对用户来说,能够更好的了解.控 制 app 涉及到的权限.然而对开发人员来说却是一件比較蛋疼的事情.须要兼容适配,并保证程序功能的正常执行. 什么叫执行时权限管理呢?在Android 6.0以下的系统中,当我们在安装应用的时候,该应用就会提示我们这个应用所须要的权限,假设你要安装.那就必须允许赋予全部权限,可是假设不允许,那就仅仅能取消安装了,有点流氓.并且安装完后,你不能够收回这个权限. 而6.0就做到了执行时权限管理.

Android6.0权限管理

Android 6.0 Marshmallow首次加入了运行时权限管理,这对用户来说,可以更好的了解.控 制 app 涉及到的权限.然而对开发者来说却是一件比较蛋疼的事情,需要兼容适配,并保证程序功能的正常运行. 什么叫运行时权限管理呢?在Android 6.0以下的系统中,当我们在安装应用的时候,该应用就会提示我们这个应用所需要的权限,如果你要安装,那就必须同意赋予所有权限,但是如果不同意,那就只能取消安装了,有点流氓.而且安装完后,你不可以收回这个权限. 而6.0就做到了运行时权限管理,即使