简单研究了一下Android6.0权限申请,在Google提供的sample的基础上,写了一个简单的demo。算是自己的笔记吧,可能会比较混乱,主要是方便以后查看。后期有别的问题,随时更新~

  • 本demo github下载地址!!!
  • Google提供的demo的下载地址
  • 6.0权限的基本知识,以下是需要单独申请的权限,共分为9组,每组只要有一个权限申请成功了,就默认整组权限都可以使用了。

    <pre class=”hljs undefined” data-original-code=”” group:android.permission-group.contacts”=”” data-snippet-id=”ext.92cf05e024a034db026f9fd16d3eb93f” data-snippet-saved=”false” data-codota-status=”done” style=”margin: 4px 0px; background-color: rgb(240, 240, 240);”>

    1. group:android.permission-group.CONTACTS
    2. permission:android.permission.WRITE_CONTACTS
    3. permission:android.permission.GET_ACCOUNTS
    4. permission:android.permission.READ_CONTACTS
    5. group:android.permission-group.PHONE
    6. permission:android.permission.READ_CALL_LOG
    7. permission:android.permission.READ_PHONE_STATE
    8. permission:android.permission.CALL_PHONE
    9. permission:android.permission.WRITE_CALL_LOG
    10. permission:android.permission.USE_SIP
    11. permission:android.permission.PROCESS_OUTGOING_CALLS
    12. permission:com.android.voicemail.permission.ADD_VOICEMAIL
    13. group:android.permission-group.CALENDAR
    14. permission:android.permission.READ_CALENDAR
    15. permission:android.permission.WRITE_CALENDAR
    16. group:android.permission-group.CAMERA
    17. permission:android.permission.CAMERA
    18. group:android.permission-group.SENSORS
    19. permission:android.permission.BODY_SENSORS
    20. group:android.permission-group.LOCATION
    21. permission:android.permission.ACCESS_FINE_LOCATION
    22. permission:android.permission.ACCESS_COARSE_LOCATION
    23. group:android.permission-group.STORAGE
    24. permission:android.permission.READ_EXTERNAL_STORAGE
    25. permission:android.permission.WRITE_EXTERNAL_STORAGE
    26. group:android.permission-group.MICROPHONE
    27. permission:android.permission.RECORD_AUDIO
    28. group:android.permission-group.SMS
    29. permission:android.permission.READ_SMS
    30. permission:android.permission.RECEIVE_WAP_PUSH
    31. permission:android.permission.RECEIVE_MMS
    32. permission:android.permission.RECEIVE_SMS
    33. permission:android.permission.SEND_SMS
    34. permission:android.permission.READ_CELL_BROADCASTS
  • 以下是普通权限,只需要在AndroidManifest.xml中申请即可。
    1. android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
    2. android.permission.ACCESS_NETWORK_STATE
    3. android.permission.ACCESS_NOTIFICATION_POLICY
    4. android.permission.ACCESS_WIFI_STATE
    5. android.permission.ACCESS_WIMAX_STATE
    6. android.permission.BLUETOOTH
    7. android.permission.BLUETOOTH_ADMIN
    8. android.permission.BROADCAST_STICKY
    9. android.permission.CHANGE_NETWORK_STATE
    10. android.permission.CHANGE_WIFI_MULTICAST_STATE
    11. android.permission.CHANGE_WIFI_STATE
    12. android.permission.CHANGE_WIMAX_STATE
    13. android.permission.DISABLE_KEYGUARD
    14. android.permission.EXPAND_STATUS_BAR
    15. android.permission.FLASHLIGHT
    16. android.permission.GET_ACCOUNTS
    17. android.permission.GET_PACKAGE_SIZE
    18. android.permission.INTERNET
    19. android.permission.KILL_BACKGROUND_PROCESSES
    20. android.permission.MODIFY_AUDIO_SETTINGS
    21. android.permission.NFC
    22. android.permission.READ_SYNC_SETTINGS
    23. android.permission.READ_SYNC_STATS
    24. android.permission.RECEIVE_BOOT_COMPLETED
    25. android.permission.REORDER_TASKS
    26. android.permission.REQUEST_INSTALL_PACKAGES
    27. android.permission.SET_TIME_ZONE
    28. android.permission.SET_WALLPAPER
    29. android.permission.SET_WALLPAPER_HINTS
    30. android.permission.SUBSCRIBED_FEEDS_READ
    31. android.permission.TRANSMIT_IR
    32. android.permission.USE_FINGERPRINT
    33. android.permission.VIBRATE
    34. android.permission.WAKE_LOCK
    35. android.permission.WRITE_SYNC_SETTINGS
    36. com.android.alarm.permission.SET_ALARM
    37. com.android.launcher.permission.INSTALL_SHORTCUT
    38. com.android.launcher.permission.UNINSTALL_SHORTCUT

申请步骤

    1. 将targetSdkVersion设置为23,注意,如果你将targetSdkVersion设置为>=23,则必须按照Android谷歌的要求,动态的申请权限,如果你暂时不打算支持动态权限申请,则targetSdkVersion*大只能设置为22.
  • 2 在AndroidManifest.xml中申请你需要的权限,包括普通权限和需要申请的特殊权限。
  • 3.开始申请权限,此处分为3部。
    • (1)检查是否由此权限checkSelfPermission(),如果已经开启,则直接做你想做的。
    • (2)如果未开启,则判断是否需要向用户解释为何申请权限shouldShowRequestPermissionRationale。
    • (3)如果需要(即返回true),则可以弹出对话框提示用户申请权限原因,用户确认后申请权限requestPermissions(),如果不需要(即返回false),则直接申请权限requestPermissions()。 (这里是一部门代码,底部有比较完善的代码,整个demo可以在github中下载)。
%title插图%num
单个权限申请.png
  1. /**
  2. * Requests permission.
  3. *
  4. * @param activity
  5. * @param requestCode request code, e.g. if you need request CAMERA permission,parameters is PermissionUtils.CODE_CAMERA
  6. */
  7. public static void requestPermission(final Activity activity, final int requestCode, PermissionGrant permissionGrant) {
  8. if (activity == null) {
  9. return;
  10. }
  11. Log.i(TAG, “requestPermission requestCode:” + requestCode);
  12. if (requestCode < 0 || requestCode >= requestPermissions.length) {
  13. Log.w(TAG, “requestPermission illegal requestCode:” + requestCode);
  14. return;
  15. }
  16. final String requestPermission = requestPermissions[requestCode];
  17. //如果是6.0以下的手机,ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED,
  18. // 但是,如果用户关闭了你申请的权限(如下图,在安装的时候,将一些权限关闭了),ActivityCompat.checkSelfPermission()则可能会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null),
  19. // 你可以使用try{}catch(){},处理异常,也可以判断系统版本,低于23就不申请权限,直接做你想做的。permissionGrant.onPermissionGranted(requestCode);
  20. // if (Build.VERSION.SDK_INT < 23) {
  21. // permissionGrant.onPermissionGranted(requestCode);
  22. // return;
  23. // }
  24. int checkSelfPermission;
  25. try {
  26. checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
  27. } catch (RuntimeException e) {
  28. Toast.makeText(activity, “please open this permission”, Toast.LENGTH_SHORT)
  29. .show();
  30. Log.e(TAG, “RuntimeException:” + e.getMessage());
  31. return;
  32. }
  33. if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
  34. Log.i(TAG, “ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED”);
  35. if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
  36. Log.i(TAG, “requestPermission shouldShowRequestPermissionRationale”);
  37. shouldShowRationale(activity, requestCode, requestPermission);
  38. } else {
  39. Log.d(TAG, “requestCameraPermission else”);
  40. ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);
  41. }
  42. } else {
  43. Log.d(TAG, “ActivityCompat.checkSelfPermission ==== PackageManager.PERMISSION_GRANTED”);
  44. Toast.makeText(activity, “opened:” + requestPermissions[requestCode], Toast.LENGTH_SHORT).show();
  45. //得到权限的时候,就可以在回调里面做你想做的事情了
  46. permissionGrant.onPermissionGranted(requestCode);
  47. }
  48. }
%title插图%num
6.0以下系统的应用程序安装界面.png

备注!!!

(1)checkSelfPermission:检查是否拥有这个权限 (2)requestPermissions:请求权限,一般会弹出一个系统对话框,询问用户是否开启这个权限。 (3)shouldShowRequestPermissionRationale:Android原生系统中,如果第二次弹出权限申请的对话框,会出现“以后不再弹出”的提示框,如果用户勾选了,你再申请权限,则shouldShowRequestPermissionRationale返回true,意思是说要给用户一个 解释,告诉用户为什么要这个权限。然而,在实际开发中,需要注意的是,很多手机对原生系统做了修改,比如小米,小米4的6.0的shouldShowRequestPermissionRationale 就一直返回false,而且在申请权限时,如果用户选择了拒*,则不会再弹出对话框了。。。。 所以说这个地方有坑,我的解决方法是,在回调里面处理,如果用户拒*了这个权限,则打开本应用信息界面,由用户自己手动开启这个权限。 (4)每个应用都有自己的权限管理界面,里面有本应用申请的权限以及各种状态,即使用户已经同意了你申请的权限,他也随时可以关闭

%title插图%num
权限管理界面.png

一次申请多个权限

其实和申请一个权限是一样的,只是requestPermissions(final @NonNull Activity activity, final @NonNull String[] permissions, final int requestCode),里面的permissions给的参数多些而已。

%title插图%num
申请多个权限.png
  1. /**
  2. * 一次申请多个权限
  3. */
  4. public static void requestMultiPermissions(final Activity activity, PermissionGrant grant) {
  5. final List<String> permissionsList = getNoGrantedPermission(activity, false);
  6. final List<String> shouldRationalePermissionsList = getNoGrantedPermission(activity, true);
  7. //TODO checkSelfPermission
  8. if (permissionsList == null || shouldRationalePermissionsList == null) {
  9. return;
  10. }
  11. Log.d(TAG, “requestMultiPermissions permissionsList:” + permissionsList.size() + “,shouldRationalePermissionsList:” + shouldRationalePermissionsList.size());
  12. if (permissionsList.size() > 0) {
  13. ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]),
  14. CODE_MULTI_PERMISSION);
  15. Log.d(TAG, “showMessageOKCancel requestPermissions”);
  16. } else if (shouldRationalePermissionsList.size() > 0) {
  17. showMessageOKCancel(activity, “should open those permission”,
  18. new DialogInterface.OnClickListener() {
  19. @Override
  20. public void onClick(DialogInterface dialog, int which) {
  21. ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),
  22. CODE_MULTI_PERMISSION);
  23. Log.d(TAG, “showMessageOKCancel requestPermissions”);
  24. }
  25. });
  26. } else {
  27. grant.onPermissionGranted(CODE_MULTI_PERMISSION);
  28. }
  29. }
  • 关于权限请求结果的回调。Activity实现ActivityCompat.OnRequestPermissionsResultCallback接口,重写onRequestPermissionsResult方法。
    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. }

整个申请权限工具类代码

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

界面调用代码

  1. package com.example.android.system.runtimepermissions;
  2. import android.os.Bundle;
  3. import android.support.annotation.NonNull;
  4. import android.support.v4.app.ActivityCompat;
  5. import android.support.v4.app.FragmentActivity;
  6. import android.support.v4.app.FragmentTransaction;
  7. import android.view.View;
  8. import android.widget.Toast;
  9. import com.example.android.common.logger.Log;
  10. /**
  11. * Created by qianxiaoai on 2016/7/8.
  12. */
  13. public class PermissionActivity extends FragmentActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
  14. private static final String TAG = PermissionActivity.class.getSimpleName();
  15. @Override
  16. public void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_permission);
  19. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  20. PermissionsFragment fragment = new PermissionsFragment();
  21. transaction.replace(R.id.content_fragment, fragment);
  22. transaction.commit();
  23. }
  24. /**
  25. * Called when the ‘show camera’ button is clicked.
  26. * Callback is defined in resource layout definition.
  27. */
  28. public void showCamera(View view) {
  29. Log.i(TAG, “Show camera button pressed. Checking permission.”);
  30. PermissionUtils.requestPermission(this, PermissionUtils.CODE_CAMERA, mPermissionGrant);
  31. }
  32. public void getAccounts(View view) {
  33. PermissionUtils.requestPermission(this, PermissionUtils.CODE_GET_ACCOUNTS, mPermissionGrant);
  34. }
  35. public void callPhone(View view) {
  36. PermissionUtils.requestPermission(this, PermissionUtils.CODE_CALL_PHONE, mPermissionGrant);
  37. }
  38. public void readPhoneState(View view) {
  39. PermissionUtils.requestPermission(this, PermissionUtils.CODE_READ_PHONE_STATE, mPermissionGrant);
  40. }
  41. public void accessFineLocation(View view) {
  42. PermissionUtils.requestPermission(this, PermissionUtils.CODE_ACCESS_FINE_LOCATION, mPermissionGrant);
  43. }
  44. public void accessCoarseLocation(View view) {
  45. PermissionUtils.requestPermission(this, PermissionUtils.CODE_ACCESS_COARSE_LOCATION, mPermissionGrant);
  46. }
  47. public void readExternalStorage(View view) {
  48. PermissionUtils.requestPermission(this, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, mPermissionGrant);
  49. }
  50. public void writeExternalStorage(View view) {
  51. PermissionUtils.requestPermission(this, PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE, mPermissionGrant);
  52. }
  53. public void recordAudio(View view) {
  54. PermissionUtils.requestPermission(this, PermissionUtils.CODE_RECORD_AUDIO, mPermissionGrant);
  55. }
  56. private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
  57. @Override
  58. public void onPermissionGranted(int requestCode) {
  59. switch (requestCode) {
  60. case PermissionUtils.CODE_RECORD_AUDIO:
  61. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_RECORD_AUDIO”, Toast.LENGTH_SHORT).show();
  62. break;
  63. case PermissionUtils.CODE_GET_ACCOUNTS:
  64. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_GET_ACCOUNTS”, Toast.LENGTH_SHORT).show();
  65. break;
  66. case PermissionUtils.CODE_READ_PHONE_STATE:
  67. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_READ_PHONE_STATE”, Toast.LENGTH_SHORT).show();
  68. break;
  69. case PermissionUtils.CODE_CALL_PHONE:
  70. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_CALL_PHONE”, Toast.LENGTH_SHORT).show();
  71. break;
  72. case PermissionUtils.CODE_CAMERA:
  73. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_CAMERA”, Toast.LENGTH_SHORT).show();
  74. break;
  75. case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
  76. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_ACCESS_FINE_LOCATION”, Toast.LENGTH_SHORT).show();
  77. break;
  78. case PermissionUtils.CODE_ACCESS_COARSE_LOCATION:
  79. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_ACCESS_COARSE_LOCATION”, Toast.LENGTH_SHORT).show();
  80. break;
  81. case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
  82. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_READ_EXTERNAL_STORAGE”, Toast.LENGTH_SHORT).show();
  83. break;
  84. case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
  85. Toast.makeText(PermissionActivity.this, “Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE”, Toast.LENGTH_SHORT).show();
  86. break;
  87. default:
  88. break;
  89. }
  90. }
  91. };
  92. /**
  93. * Callback received when a permissions request has been completed.
  94. */
  95. @Override
  96. public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
  97. @NonNull int[] grantResults) {
  98. PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
  99. }
  100. }

xml布局

  1. <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
  2. android:layout_width=“match_parent”
  3. android:layout_height=“match_parent”
  4. android:paddingLeft=“@dimen/horizontal_page_margin”
  5. android:paddingRight=“@dimen/horizontal_page_margin”
  6. android:paddingTop=“@dimen/vertical_page_margin”
  7. android:paddingBottom=“@dimen/vertical_page_margin”
  8. android:orientation=“vertical”
  9. >
  10. <FrameLayout
  11. android:id=“@+id/content_fragment”
  12. android:layout_width=“match_parent”
  13. android:layout_height=“0dp”
  14. android:layout_weight=“1”/>
  15. <ScrollView
  16. android:layout_width=“match_parent”
  17. android:layout_height=“0dp”
  18. android:layout_weight=“1”>
  19. <LinearLayout
  20. android:layout_width=“match_parent”
  21. android:layout_height=“match_parent”
  22. android:orientation=“vertical”>
  23. <LinearLayout
  24. android:layout_width=“match_parent”
  25. android:layout_height=“wrap_content”
  26. android:orientation=“horizontal”>
  27. <Button
  28. android:layout_width=“wrap_content”
  29. android:layout_height=“wrap_content”
  30. android:text=“Camera”
  31. android:id=“@+id/button_camera”
  32. android:onClick=“showCamera”/>
  33. <Button
  34. android:layout_width=“wrap_content”
  35. android:layout_height=“wrap_content”
  36. android:text=“RECORD_AUDIO”
  37. android:onClick=“recordAudio”/>
  38. </LinearLayout>
  39. <LinearLayout
  40. android:layout_width=“match_parent”
  41. android:layout_height=“wrap_content”
  42. android:orientation=“horizontal”>
  43. <Button
  44. android:layout_width=“wrap_content”
  45. android:layout_height=“wrap_content”
  46. android:text=“GET_ACCOUNTS”
  47. android:onClick=“getAccounts”/>
  48. <Button
  49. android:layout_width=“wrap_content”
  50. android:layout_height=“wrap_content”
  51. android:text=“CALL_PHONE”
  52. android:onClick=“callPhone”/>
  53. </LinearLayout>
  54. <Button
  55. android:layout_width=“wrap_content”
  56. android:layout_height=“wrap_content”
  57. android:text=“PERMISSION_READ_PHONE_STATE”
  58. android:onClick=“readPhoneState”/>
  59. <Button
  60. android:layout_width=“wrap_content”
  61. android:layout_height=“wrap_content”
  62. android:text=“ACCESS_FINE_LOCATION”
  63. android:onClick=“accessFineLocation”/>
  64. <Button
  65. android:layout_width=“wrap_content”
  66. android:layout_height=“wrap_content”
  67. android:text=“ACCESS_COARSE_LOCATION”
  68. android:onClick=“accessCoarseLocation”/>
  69. <Button
  70. android:layout_width=“wrap_content”
  71. android:layout_height=“wrap_content”
  72. android:text=“READ_EXTERNAL_STORAGE”
  73. android:onClick=“readExternalStorage”/>
  74. <Button
  75. android:layout_width=“wrap_content”
  76. android:layout_height=“wrap_content”
  77. android:text=“WRITE_EXTERNAL_STORAGE”
  78. android:onClick=“writeExternalStorage”/>
  79. </LinearLayout>
  80. </ScrollView>
  81. </LinearLayout>

清单文件申请的权限

  1. <uses-permission android:name=“android.permission.CAMERA”/>
  2. <uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION”/>
  3. <uses-permission android:name=“android.permission.ACCESS_COARSE_LOCATION”/>
  4. <uses-permission android:name=“android.permission.CALL_PHONE”/>
  5. <uses-permission android:name=“android.permission.SEND_SMS”/>
  6. <uses-permission android:name=“android.permission.READ_SMS”/>
  7. <uses-permission android:name=“android.permission.GET_ACCOUNTS”/>
  8. <uses-permission android:name=“android.permission.READ_PHONE_STATE”/>
  9. <uses-permission android:name=“android.permission.READ_EXTERNAL_STORAGE”/>
  10. <uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”/>
  11. <uses-permission android:name=“android.permission.RECORD_AUDIO”/>

部分 资源文件

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