Android6.0权限申请工具类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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   } 

 

以上是关于Android6.0权限申请工具类的主要内容,如果未能解决你的问题,请参考以下文章

Android 动态申请权限工具类

android6.0权限管理工具EasyPermissionUtil

Android6.0------权限申请RxPermissions

Android6.0------权限申请~easypermissions

android6.0以上权限动态申请

Android6.0动态权限申请