Android动态权限申请工具类非常好用包含9组危险权限
生活随笔
收集整理的這篇文章主要介紹了
Android动态权限申请工具类非常好用包含9组危险权限
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
先看下動態(tài)權限的工具類:
package com.xiayiye.yhsh.permissionsdemo;import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.widget.Toast;import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;/*** @author :下一頁5(輕飛揚)* 創(chuàng)建時間:2018/5/22.20:23*/ public class PermissionUtils {private static final String TAG = PermissionUtils.class.getSimpleName();public static final int CODE_RECORD_AUDIO = 0;public static final int CODE_GET_ACCOUNTS = 1;public static final int CODE_READ_PHONE_STATE = 2;public static final int CODE_CALL_PHONE = 3;public static final int CODE_CAMERA = 4;public static final int CODE_ACCESS_FINE_LOCATION = 5;public static final int CODE_ACCESS_COARSE_LOCATION = 6;public static final int CODE_READ_EXTERNAL_STORAGE = 7;public static final int CODE_WRITE_EXTERNAL_STORAGE = 8;public static final int CODE_MULTI_PERMISSION = 100;public static final String PERMISSION_RECORD_AUDIO = Manifest.permission.RECORD_AUDIO;public static final String PERMISSION_GET_ACCOUNTS = Manifest.permission.GET_ACCOUNTS;public static final String PERMISSION_READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE;public static final String PERMISSION_CALL_PHONE = Manifest.permission.CALL_PHONE;public static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;public static final String PERMISSION_ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;public static final String PERMISSION_ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;public static final String PERMISSION_READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;public static final String PERMISSION_WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;private static final String[] requestPermissions = {PERMISSION_RECORD_AUDIO,PERMISSION_GET_ACCOUNTS,PERMISSION_READ_PHONE_STATE,PERMISSION_CALL_PHONE,PERMISSION_CAMERA,PERMISSION_ACCESS_FINE_LOCATION,PERMISSION_ACCESS_COARSE_LOCATION,PERMISSION_READ_EXTERNAL_STORAGE,PERMISSION_WRITE_EXTERNAL_STORAGE};interface PermissionGrant {void onPermissionGranted(int requestCode);}/*** Requests permission.** @param activity* @param requestCode request code, e.g. if you need request CAMERA permission,parameters is PermissionUtils.CODE_CAMERA*/public static void requestPermission(final Activity activity, final int requestCode, PermissionGrant permissionGrant) {if (activity == null) {return;}Log.i(TAG, "requestPermission requestCode:" + requestCode);if (requestCode < 0 || requestCode >= requestPermissions.length) {Log.w(TAG, "requestPermission illegal requestCode:" + requestCode);return;}final String requestPermission = requestPermissions[requestCode];//如果是6.0以下的手機,ActivityCompat.checkSelfPermission()會始終等于PERMISSION_GRANTED,// 但是,如果用戶關閉了你申請的權限,ActivityCompat.checkSelfPermission(),會導致程序崩潰(java.lang.RuntimeException: Unknown exception code: 1 msg null),// 你可以使用try{}catch(){},處理異常,也可以在這個地方,低于23就什么都不做,// 個人建議try{}catch(){}單獨處理,提示用戶開啟權限。if (Build.VERSION.SDK_INT < 23) {return;}int checkSelfPermission;try {checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);} catch (RuntimeException e) {Toast.makeText(activity, "please open this permission", Toast.LENGTH_SHORT).show();Log.e(TAG, "RuntimeException:" + e.getMessage());return;}if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {Log.i(TAG, "ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED");if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {Log.i(TAG, "requestPermission shouldShowRequestPermissionRationale");shouldShowRationale(activity, requestCode, requestPermission);} else {Log.d(TAG, "requestCameraPermission else");ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);}} else {Log.d(TAG, "ActivityCompat.checkSelfPermission ==== PackageManager.PERMISSION_GRANTED");Toast.makeText(activity, "opened:" + requestPermissions[requestCode], Toast.LENGTH_SHORT).show();permissionGrant.onPermissionGranted(requestCode);}}private static void requestMultiResult(Activity activity, String[] permissions, int[] grantResults, PermissionGrant permissionGrant) {if (activity == null) {return;}//TODOLog.d(TAG, "onRequestPermissionsResult permissions length:" + permissions.length);Map<String, Integer> perms = new HashMap<>();ArrayList<String> notGranted = new ArrayList<>();for (int i = 0; i < permissions.length; i++) {Log.d(TAG, "permissions: [i]:" + i + ", permissions[i]" + permissions[i] + ",grantResults[i]:" + grantResults[i]);perms.put(permissions[i], grantResults[i]);if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {notGranted.add(permissions[i]);}}if (notGranted.size() == 0) {Toast.makeText(activity, "all permission success" + notGranted, Toast.LENGTH_SHORT).show();permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION);} else {openSettingActivity(activity, "those permission need granted!");}}/*** 一次申請多個權限*/public static void requestMultiPermissions(final Activity activity, PermissionGrant grant) {final List<String> permissionsList = getNoGrantedPermission(activity, false);final List<String> shouldRationalePermissionsList = getNoGrantedPermission(activity, true);//TODO checkSelfPermissionif (permissionsList == null || shouldRationalePermissionsList == null) {return;}Log.d(TAG, "requestMultiPermissions permissionsList:" + permissionsList.size() + ",shouldRationalePermissionsList:" + shouldRationalePermissionsList.size());if (permissionsList.size() > 0) {ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]),CODE_MULTI_PERMISSION);Log.d(TAG, "showMessageOKCancel requestPermissions");} else if (shouldRationalePermissionsList.size() > 0) {showMessageOKCancel(activity, "should open those permission",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),CODE_MULTI_PERMISSION);Log.d(TAG, "showMessageOKCancel requestPermissions");}});} else {grant.onPermissionGranted(CODE_MULTI_PERMISSION);}}private static void shouldShowRationale(final Activity activity, final int requestCode, final String requestPermission) {//TODOString[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);showMessageOKCancel(activity, "Rationale: " + permissionsHint[requestCode], new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {ActivityCompat.requestPermissions(activity,new String[]{requestPermission},requestCode);Log.d(TAG, "showMessageOKCancel requestPermissions:" + requestPermission);}});}private static void showMessageOKCancel(final Activity context, String message, DialogInterface.OnClickListener okListener) {new AlertDialog.Builder(context).setMessage(message).setPositiveButton("打開權限", okListener).setNegativeButton("取消", null).create().show();}/*** @param activity* @param requestCode Need consistent with requestPermission* @param permissions* @param grantResults*/public static void requestPermissionsResult(final Activity activity, final int requestCode, String[] permissions,int[] grantResults, PermissionGrant permissionGrant) {if (activity == null) {return;}Log.d(TAG, "requestPermissionsResult requestCode:" + requestCode);if (requestCode == CODE_MULTI_PERMISSION) {requestMultiResult(activity, permissions, grantResults, permissionGrant);return;}if (requestCode < 0 || requestCode >= requestPermissions.length) {Log.w(TAG, "requestPermissionsResult illegal requestCode:" + requestCode);Toast.makeText(activity, "illegal requestCode:" + requestCode, Toast.LENGTH_SHORT).show();return;}Log.i(TAG, "onRequestPermissionsResult requestCode:" + requestCode + ",permissions:" + permissions.toString()+ ",grantResults:" + grantResults.toString() + ",length:" + grantResults.length);if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {Log.i(TAG, "onRequestPermissionsResult PERMISSION_GRANTED");//TODO success, do something, can use callbackpermissionGrant.onPermissionGranted(requestCode);} else {//TODO hint user this permission functionLog.i(TAG, "onRequestPermissionsResult PERMISSION NOT GRANTED");//TODOString[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);openSettingActivity(activity, "Result" + permissionsHint[requestCode]);}}private static void openSettingActivity(final Activity activity, String message) {showMessageOKCancel(activity, message, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Intent intent = new Intent();intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);Log.d(TAG, "getPackageName(): " + activity.getPackageName());Uri uri = Uri.fromParts("package", activity.getPackageName(), null);intent.setData(uri);activity.startActivity(intent);}});}/*** @param activity* @param isShouldRationale true: return no granted and shouldShowRequestPermissionRationale permissions, false:return no granted and !shouldShowRequestPermissionRationale* @return*/public static ArrayList<String> getNoGrantedPermission(Activity activity, boolean isShouldRationale) {ArrayList<String> permissions = new ArrayList<>();for (int i = 0; i < requestPermissions.length; i++) {String requestPermission = requestPermissions[i];//TODO checkSelfPermissionint checkSelfPermission = -1;try {checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);} catch (RuntimeException e) {Toast.makeText(activity, "please open those permission", Toast.LENGTH_SHORT).show();Log.e(TAG, "RuntimeException:" + e.getMessage());return null;}if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {Log.i(TAG, "getNoGrantedPermission ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED:" + requestPermission);if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {Log.d(TAG, "shouldShowRequestPermissionRationale if");if (isShouldRationale) {permissions.add(requestPermission);}} else {if (!isShouldRationale) {permissions.add(requestPermission);}Log.d(TAG, "shouldShowRequestPermissionRationale else");}}}return permissions;} }再看下如何調用
看不懂的可以下載moudle源碼跑起來
點擊下載源碼
總結
以上是生活随笔為你收集整理的Android动态权限申请工具类非常好用包含9组危险权限的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 孤岛惊魂4图文全攻略 主线:文化交流(1
- 下一篇: 我的世界OptiFine安装方法图文教程