当前位置:   article > 正文

Android应用权限请求步骤_android 请求权限

android 请求权限

1.在AndroidManifest.xml中配置请求权限

  1. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2.在onCreate(Bundle savedInstanceState)方法中请求权限

  1. //授权请求
  2. if (Build.VERSION.SDK_INT >= 24) {
  3. System.out.println("版本正确");
  4. checkPermission();
  5. }else {
  6. System.out.println("版本过低");
  7. }

权限检测实现代码

  1. private static final int REQUEST_CODE = 1;
  2. private static String[] PERMISSIONS_STORAGE = {
  3. "android.permission.READ_EXTERNAL_STORAGE",
  4. "android.permission.WRITE_EXTERNAL_STORAGE"};
  5. //授权检测
  6. private void checkPermission() {
  7. //权限是否已经赋予
  8. if (m_activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
  9. != PackageManager.PERMISSION_GRANTED) {
  10. //未赋予权限,申请权限
  11. if (m_activity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  12. //选择不开启权限的时候,提示用户
  13. Toast.makeText(m_activity.getApplicationContext() , "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
  14. }
  15. //申请权限
  16. m_activity.requestPermissions( PERMISSIONS_STORAGE, REQUEST_CODE);
  17. } else {
  18. //权限已赋予
  19. Toast.makeText(m_activity.getApplicationContext(), "已授权成功!", Toast.LENGTH_SHORT).show();
  20. }
  21. }

权限请求结果代码

  1. public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  2. switch (requestCode) {
  3. //权限的申请结果返回
  4. case REQUEST_CODE: {
  5. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  6. //已授权
  7. Toast.makeText(m_activity.getApplicationContext(), "授权成功!", Toast.LENGTH_SHORT).show();
  8. } else {
  9. //未授权
  10. Toast.makeText(m_activity.getApplicationContext(), "授权被拒绝!", Toast.LENGTH_SHORT).show();
  11. }
  12. }
  13. }
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/283770
推荐阅读
相关标签
  

闽ICP备14008679号