Android之动态申请权限

这篇具有很好参考价值的文章主要介绍了Android之动态申请权限。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


Android 6.0 (API 23) 之前应用的权限在安装时全部授予,运行时应用不再需要询问用户。在 Android 6.0 或更高版本对权限进行了分类,对某些涉及到用户隐私的权限可在运行时根据用户的需要动态授予。
Android 6.0以下,在AndroidManifest.xml文件中注册权限即可。
Android 6.0及其以后,既要在AndroidManifest.xml文件中注册,又要动态申请危险权限。

如果没有进行动态申请权限将报下面的权限问题的错
android 动态申请权限,Android,android,android studio,java

1.动态申请权限

打电话的动态申请权限例子

package com.example.androidnetwork;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.jetbrains.annotations.NotNull;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.os.Build.VERSION_CODES.M;

public class TestActivity extends AppCompatActivity {


    private static final String TAG = "TestActivity";
    private Button mButton;
    //请求码
    private int REQUESTCODE=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ButterKnife.bind(this);
        mButton = findViewById(R.id.buttonTest);
       // getExternalFilesDir(Environment.DIRECTORY_PICTURES);

    }

    private void checkPermission() {
        //1.判断当前手机系统是否大于或等于6.0
        //4.如果有打电话的授权,就直接拨打电话
        //1.判断当前手机系统是否大于或等于6.0
        if(Build.VERSION.SDK_INT>=M){
            //2.如果大于6.0,则检查是否有打电话的权限授权
            int isPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);//用于检测程序是否包含某项权限
            //下面的log如果程序第一次运行checkPermission一般是-1,需要下面的ActivityCompat.requestPermissions去动态
            //申请权限,当你动态申请过一次后下次就不是-1了,除非删掉程序。
            Log.d(TAG, "checkPermission: "+isPermission);
            if(isPermission== PackageManager.PERMISSION_GRANTED){
                //4.如果有打电话的授权,就直接拨打电话
                call();
            }else {
                //3.如果没有打电话的授权,就要去申请打电话的权限
                //下面为申请权限的方法,下面的onRequestPermissionsResult方法用于验证此方法申请成功或失败(到时会弹出一个对话框给你选择允许拒绝)
                //也会导致回调onRequestPermissionsResult方法
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},REQUESTCODE);
            }
        }else {
            //5.如果当前版本小于6.0,直接拨打电话
            call();
        }
    }

    /*
    此函数为申请权限的回调方法,无论成功或者失败,都会回调这个方法
    requestCode:上文中提到的请求码
    permissions:申请的权限
    grantResults:申请的结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==REQUESTCODE){
            if(grantResults!=null&&grantResults.length>0){
                //判断用户是否授予了这个权限
                //因为目前只有打电话这一个权限结果所以使用grantResults[0]
                if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    call();
                }else {
                    Toast.makeText(this,"您拒绝了拨打电话的权限",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public void call(){
       //下面这个可以使用this的原因是编译时,他没有new一个实现类或者内部类,不然的话就要类名.this
       //Toast.makeText(this,"你好啊",Toast.LENGTH_SHORT).show();
       Intent intent = new Intent(Intent.ACTION_CALL);
       Uri uri = Uri.parse("tel:" + 1008611);
       intent.setData(uri);
       startActivity(intent);
       Log.d(TAG, "text: "+"跳转了");
   }
    public void text(View view){
       checkPermission();
    }
}

PackageManager.PERMISSION_GRANTED 与 PackageManager.PERMISSION_DENIED ,分别代表着有权限与无权限。通常我们会根据当前权限的状态来决定是否去申请相关权限。

具体内容可看程序注释,比较详细

2.动态申请权限工具类的封装

封装工具类

package com.example.androidnetwork.utils;

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.util.Log;

import android.widget.Toast;


import androidx.core.app.ActivityCompat;

/*
申请多个权限的工具类
 */
public class PermissionUtils {
    //请求码
    public final static int CODE_RECERD_AUDIO = 0;
    public final static int CODE_GET_ACCOUNTS = 1;
    public final static int CODE_READ_PHONE_STATE = 2;
    public final static int CODE_CALL_PHONE = 3;
    public final static int CODE_CAMERA = 4;
    public final static int CODE_ACCESS_FINE_LOCATION = 5;
    public final static int CODE_ACCESS_COARSE_LOCATION = 6;
    public final static int CODE_READ_EXTERNAL_STORAGE = 7;
    public final static int CODE_WRITE_EXTERNAL_STORAGE = 8;

    //权限的名称
    public static final String PERMISSION_RECERD_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_RECERD_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
    };
    private static final String TAG = "PermissionUtils";

    //表示授权成功的接口
    public interface PermissionGrant{
        void onPermissionGranted(int requestCode);
    }
    /*
    封装请求权限的函数
     */
    public  static void requestPermission(Activity activity,int requestCode,PermissionGrant permissionGrant){
        if(activity==null){
            return;
        }
        //排除不存在的请求码
        if(requestCode<0||requestCode>=requestPermissions.length){
            return;
        }
        String requestPermission = requestPermissions[requestCode];
        //小于6.0的默认授权状态
        if(Build.VERSION.SDK_INT<23){
            return;
        }
        //大于6.0申请授权
        int checkSelfPermission ;
        try {
            checkSelfPermission= ActivityCompat.checkSelfPermission(activity,requestPermission);
        }catch (Exception e){
            Toast.makeText(activity,"请打开这个权限:"+requestPermission,Toast.LENGTH_SHORT).show();
            return;
        }
        //判断是否被授权了
        if(checkSelfPermission!= PackageManager.PERMISSION_GRANTED){
            //没有被授权,需要进行申请
            if(ActivityCompat.shouldShowRequestPermissionRationale(activity,requestPermission)){
                //判断申请的权限是否需要弹出对话框
                shouldShowRationale(activity,requestCode,requestPermission);
            }else {
                ActivityCompat.requestPermissions(activity,new String[]{requestPermission},requestCode);
            }
        }else {
            //用户授权了,可以直接调用相关功能
            Toast.makeText(activity,"opened:"+requestPermission,Toast.LENGTH_SHORT).show();
            permissionGrant.onPermissionGranted(requestCode);
        }
    }

    private static void shouldShowRationale(Activity activity, int requestCode, String requestPermission) {
        showMessageOKCancel(activity, "Rationale" + requestPermission, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityCompat.requestPermissions(activity,new String[]{requestPermission},requestCode);
            }
        });
    }

    /*
    申请权限结果的方法
     */
    public static void requestPermissionsResult(Activity activity,int requestCode,
                                                String[] permissions, int[] grantResults,PermissionGrant permissionGrant){
        if(activity==null){
            return;
        }
        if(requestCode<0||requestCode>=requestPermissions.length){
            Toast.makeText(activity,"illegar requestCode:"+requestCode, Toast.LENGTH_SHORT).show();
            return;
        }
        if(grantResults.length==1&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
            //授权成功了(也就是点击允许了)
            permissionGrant.onPermissionGranted(requestCode);
        }else {
            //获取请求码对应的请求信息
            String permissionError =requestPermissions[requestCode];
            openSettingActivity(activity,"Result"+permissionError);
        }
    }
    //打开设置页面
    private static void openSettingActivity(Activity activity, String msg) {
        showMessageOKCancel(activity, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                intent.setData(uri);
                activity.startActivity(intent);
            }
        });
    }
    //弹出是否打开的对话框
    private static void showMessageOKCancel(Activity activity, String msg, DialogInterface.OnClickListener oklistener){
        new AlertDialog.Builder(activity)
                .setMessage(msg)
                .setPositiveButton("OK",oklistener)
                .setNegativeButton("Cancel",null)
                .create().show();
    }
}

使用工具类

package com.example.androidnetwork;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.androidnetwork.utils.PermissionUtils;

import org.jetbrains.annotations.NotNull;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.os.Build.VERSION_CODES.M;

public class TestActivity extends AppCompatActivity {


    private static final String TAG = "TestActivity";
    private Button mButton;
    //请求码
    private int REQUESTCODE=1;
   PermissionUtils.PermissionGrant permissionGrant= new PermissionUtils.PermissionGrant() {

       @Override
       public void onPermissionGranted(int requestCode) {
           //onPermissionGranted方法里面执行你需要申请动态权限的内容
           call();
       }

   };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ButterKnife.bind(this);
        mButton = findViewById(R.id.buttonTest);
       // getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        PermissionUtils.requestPermission(this, PermissionUtils.CODE_CALL_PHONE, permissionGrant);

    }

 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: "+permissions.length);
        PermissionUtils.requestPermissionsResult(this,requestCode,permissions,grantResults,permissionGrant);
    }

    public void call(){
       //下面这个可以使用this的原因是编译时,他没有new一个实现类或者内部类,不然的话就要类名.this
       //Toast.makeText(this,"你好啊",Toast.LENGTH_SHORT).show();
       Intent intent = new Intent(Intent.ACTION_CALL);
       Uri uri = Uri.parse("tel:" + 1008611);
       intent.setData(uri);
       startActivity(intent);
       Log.d(TAG, "text: "+"跳转了");
   }
    public void text(View view){
      // checkPermission();
       call();

    }
}

android 动态申请权限,Android,android,android studio,java
android 动态申请权限,Android,android,android studio,java

shouldShowRequestPermissionRationale,回到最初的解释“应不应该解释下请求这个权限的目的”。
1.都没有请求过这个权限,用户不一定会拒绝你,所以你不用解释,故返回false;
2.请求了但是被拒绝了,此时返回true,意思是你该向用户好好解释下了;
(也就是你第一次进行申请的时候弹出的对话框你选择了拒绝,那么就会返回true)
3.请求权限被禁止了,也不给你弹窗提醒了,所以你也不用解释了,故返回fasle;
4.请求被允许了,都给你权限了,还解释个啥,故返回false。
Google的初衷大概就是第一次requestPermissions的时候被拒绝时给你一次解释的机会,所以是让你在请求权限的回调中使用的。文章来源地址https://www.toymoban.com/news/detail-765641.html

3.一次申请多个权限的方法

 //    申请多个权限的请求码
    public final static int CODE_MULTI_PERMISSION = 100;
  /* 一次申请多个权限*/
    public static void requestMultiPermissions(final Activity activity, PermissionGrant grant){
        //获取没有被授权的权限
        ArrayList<String> permissionList = getNoGrantedPermission(activity, false);
        final ArrayList<String> shouldRationalePermissionList = getNoGrantedPermission(activity, true);
        if(permissionList==null||shouldRationalePermissionList==null){
            return;
        }

        if (permissionList.size()>0) {
            ActivityCompat.requestPermissions(activity,permissionList.toArray(new String[permissionList.size()]),
                    CODE_MULTI_PERMISSION);
        }else if (shouldRationalePermissionList.size()>0){
            showMessageOKCancel(activity, "should open those permissions", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(activity,
                            shouldRationalePermissionList.toArray(new String[shouldRationalePermissionList.size()]),CODE_MULTI_PERMISSION);
                }
            });
        }else {
            grant.onPermissionGranted(CODE_MULTI_PERMISSION);
        }
    }

    /*
    * 获取没有被授权的权限列表
    * */
    private 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];
           int checkSelfPermission = -1;
           try {
               checkSelfPermission = ActivityCompat.checkSelfPermission(activity,requestPermission);
           }catch (Exception e){
               Toast.makeText(activity,"please open those permission",Toast.LENGTH_SHORT).show();
               return null;
           }

           if (checkSelfPermission!=PackageManager.PERMISSION_GRANTED){
//               没有被授权需要去申请
               if (ActivityCompat.shouldShowRequestPermissionRationale(activity,requestPermission)) {
                   if (isShouldRationale) {
                       permissions.add(requestPermission);
                   }
               }else {
                   if (!isShouldRationale){
                       permissions.add(requestPermission);
                   }
               }
           }
        }

        return permissions;
    }
     /*
    * 获取申请多个权限的结果
    * */
    public static void requestMultiResult(Activity activity,@NonNull String[] permissions, @NonNull int[] grantResults,
                                          PermissionGrant permissionGrant){
        if (activity == null) {
            return;
        }
        Map<String,Integer>perms = new HashMap<>();
        ArrayList<String> notGranted = new ArrayList<>();
        for (int i = 0; i < permissions.length; 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 succewss",Toast.LENGTH_SHORT).show();
            permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION);
        }else {
            openSettingActivity(activity,"those permission need granted!");
        }

    }

4.最终整个工具类

package com.animee.loadweb;
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.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/* 申请多个权限的工具类*/
public class PermissonUtils {
    public final static int CODE_RECERD_AUDIO = 0;
    public final static int CODE_GET_ACCOUNTS = 1;
    public final static int CODE_READ_PHONE_STATE = 2;
    public final static int CODE_CALL_PHONE = 3;
    public final static int CODE_CAMERA = 4;
    public final static int CODE_ACCESS_FINE_LOCATION = 5;
    public final static int CODE_ACCESS_COARSE_LOCATION = 6;
    public final static int CODE_READ_EXTERNAL_STORAGE = 7;
    public final static int CODE_WRITE_EXTERNAL_STORAGE = 8;
//    申请多个权限的请求码
    public final static int CODE_MULTI_PERMISSION = 100;

    public static final String PERMISSION_RECERD_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_RECERD_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
    };
// 表示授权成功的接口
    public  interface PermissionGrant{
        void onPermissionGranted(int requestCode);
    }
    /*
    * 封装请求权限的函数
    * */
    public static void requestPermission(Activity activity,int requestCode,PermissionGrant permissionGrant){
        if (activity == null) {
            return;
        }
//        排除不存在的请求码
        if(requestCode< 0||requestCode>=requestPermissions.length){
            return;
        }

        String requestPermission = requestPermissions[requestCode];
//       小于6.0默认授权状态
        if(Build.VERSION.SDK_INT<23){
            return;
        }
        int checkSelfPermission;
        try {
            checkSelfPermission = ActivityCompat.checkSelfPermission(activity,requestPermission);
        }catch (Exception e){
            Toast.makeText(activity,"请打开这个权限:"+requestPermission,Toast.LENGTH_SHORT).show();
            return;
        }
        //判断是否被授权了
        if (checkSelfPermission!= PackageManager.PERMISSION_GRANTED) {
            // 没有被授权,需要进行申请
            if(ActivityCompat.shouldShowRequestPermissionRationale(activity,requestPermission)){
                shouldShowRationale(activity,requestCode,requestPermission);
            }else {
                ActivityCompat.requestPermissions(activity,new String[]{requestPermission},requestCode);
            }
        }else {
            //用户授权了,可以直接调用相关功能
            Toast.makeText(activity,"opened:"+requestPermission,Toast.LENGTH_SHORT).show();
            permissionGrant.onPermissionGranted(requestCode);
        }
    }

    private static void shouldShowRationale(final Activity activity, final int requestCode, final String requestPermission) {
        showMessageOKCancel(activity, "Rationale:" + requestPermission, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityCompat.requestPermissions(activity,new String[]{requestPermission},requestCode);
            }
        });
    }

    /*
    * 申请权限结果的方法
    * */
    public static void requestPermissionsResult(Activity activity, int requestCode,
                                                @NonNull String[] permissions, @NonNull int[] grantResults,PermissionGrant permissionGrant){
        if (activity == null) {
            return;
        }
        if(requestCode<0||requestCode>=requestPermissions.length){
            Toast.makeText(activity,"illegal requestCode:"+requestCode,Toast.LENGTH_SHORT).show();
            return;
        }

        if(grantResults.length==1&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
//            授权成功了
            permissionGrant.onPermissionGranted(requestCode);
        }else {
            String permissionError = permissions[requestCode];
            openSettingActivity(activity,"Result:"+permissionError);
        }
    }
    /*
    * 获取申请多个权限的结果
    * */
    public static void requestMultiResult(Activity activity,@NonNull String[] permissions, @NonNull int[] grantResults,
                                          PermissionGrant permissionGrant){
        if (activity == null) {
            return;
        }
        Map<String,Integer>perms = new HashMap<>();
        ArrayList<String> notGranted = new ArrayList<>();
        for (int i = 0; i < permissions.length; 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 succewss",Toast.LENGTH_SHORT).show();
            permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION);
        }else {
            openSettingActivity(activity,"those permission need granted!");
        }

    }
    /*打开设置界面*/
    private static void openSettingActivity(final Activity activity, String msg) {
        showMessageOKCancel(activity, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                intent.setData(uri);
                activity.startActivity(intent);
            }
        });
    }

    /* 弹出是否打开的对话框*/
    private static void showMessageOKCancel(Activity activity, String msg, DialogInterface.OnClickListener oklistener){
        new AlertDialog.Builder(activity)
                .setMessage(msg)
                .setPositiveButton("OK",oklistener)
                .setNegativeButton("Cancel",null)
                .create().show();
    }

    /* 一次申请多个权限*/
    public static void requestMultiPermissions(final Activity activity, PermissionGrant grant){
        //获取没有被授权的权限
        ArrayList<String> permissionList = getNoGrantedPermission(activity, false);
        final ArrayList<String> shouldRationalePermissionList = getNoGrantedPermission(activity, true);
        if(permissionList==null||shouldRationalePermissionList==null){
            return;
        }

        if (permissionList.size()>0) {
            ActivityCompat.requestPermissions(activity,permissionList.toArray(new String[permissionList.size()]),
                    CODE_MULTI_PERMISSION);
        }else if (shouldRationalePermissionList.size()>0){
            showMessageOKCancel(activity, "should open those permissions", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(activity,
                            shouldRationalePermissionList.toArray(new String[shouldRationalePermissionList.size()]),CODE_MULTI_PERMISSION);
                }
            });
        }else {
            grant.onPermissionGranted(CODE_MULTI_PERMISSION);
        }
    }

    /*
    * 获取没有被授权的权限列表
    * */
    private 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];
           int checkSelfPermission = -1;
           try {
               checkSelfPermission = ActivityCompat.checkSelfPermission(activity,requestPermission);
           }catch (Exception e){
               Toast.makeText(activity,"please open those permission",Toast.LENGTH_SHORT).show();
               return null;
           }

           if (checkSelfPermission!=PackageManager.PERMISSION_GRANTED){
//               没有被授权需要去申请
               if (ActivityCompat.shouldShowRequestPermissionRationale(activity,requestPermission)) {
                   if (isShouldRationale) {
                       permissions.add(requestPermission);
                   }
               }else {
                   if (!isShouldRationale){
                       permissions.add(requestPermission);
                   }
               }
           }
        }

        return permissions;
    }
}

到了这里,关于Android之动态申请权限的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • android 12 SD动态申请读写权限

    android 12不仅需要在AndroidManifest.xml申请读写权限也需要在代码中动态的申请 关于如何动态申请读写权限仅需要两步 在AndroidManifest.xml文件中申请读写权限 在代码的启动MainActivity中动态申请方法 下面是关于动态权限申请的Manifest.class类大家有兴趣可以去了解下

    2024年02月11日
    浏览(42)
  • Android申请权限(相机权限和读写权限)

    开发一个相机应用,需要申请三个权限:相机、读文件、写文件。 初步授权成功

    2024年02月11日
    浏览(54)
  • Android 开发中的权限申请

            我们都知道,从 Android 6.0 开始,部分危险权限在 xml 注册的同时,还需要动态申请。 1、需要动态申请的权限         需要动态申请的权限主要分为这 9 类,当然每类中可能不止一个权限,但只要动态申请一个就默认获取整个类别的权限。 2、申请单个权限   

    2024年02月09日
    浏览(55)
  • android11 申请所有文件访问权限

    Android 11 引入了强制执行分区存储的限制,导致应用默认不能访问外部文件。 针对以前涉及较多文件的操作,可采用申请所有文件访问权限的方式来解决这一问题,实现方式如下。 (虽然这样做安全性低,官方并不推荐这样,但确实最快适配原有应用程序的方式) 1. Android

    2024年02月04日
    浏览(45)
  • Android11及以上 文件读写权限申请

    Android11 读写权限申请 Android11系统对应用写入权限做了严格的限制。本文介绍如何获取文件读写权限。项目中 build.gradle 的 targetSdkVersion = 29 ,会出现读写问题。 当 targetSdkVersion = 29,通过设置requestLegacyExternalStorage=“true”,还能解决。 当 targetSdkVersion = 30后,需要申请所有文件

    2023年04月10日
    浏览(60)
  • android 11后文件读写访问权限申请

    android 11后对文件读写访问权限管理 与 android 10又有了新的要求,导致在读写或者访问时出现error:java.io.FileNotFoundException: /storage/emulated/0/file_path open failed: EACCES (Permission denied),以下为android 11文件管理权限申请办法 回忆android 10 文件访问权限申请 step 1: AndroidManifest中添加权限申

    2024年02月05日
    浏览(47)
  • Android 获取SIM卡号码权限申请

    在AndroidManifest.xml中添加如下权限 uses-permission android:name=\\\"android.permission.READ_PHONE_STATE\\\"/ 如果你只在清单文件中添加权限却没有在代码中获取权限,代码还是会报错的。 报错原因: android 6.0以上增加了动态获取权限api,需要动态获取手机的权限。弹出对话框询问用户,请求用户

    2024年02月08日
    浏览(42)
  • Unity 在Unity端申请Android权限

    前段时间还在职的时候,遇到这么一个问题:SDK首次调起相机接口进行拍照的时候,会调起2次相机。并在第2次拍照后闪退。 分析了一下,都是发生在首次获取权限时才会发生,拿到权限就不会了。并且2台会发生这种情况的Android版本都是13。猜测是SDK获取权限接口没有适配好

    2024年02月15日
    浏览(44)
  • Android Permission 权限申请,EasyPermission和其他三方库

    在Android的实际开发中,经常会因为需求的实现,需要申请用户权限。 今天总结下Android中常用的权限申请。 一、基本介绍和流程 Android中的权限申请是通过应用程序与操作系统之间的交互实现的。在Android中,每个应用程序都被赋予了一组预定义的权限,这些权限定义了应用程

    2024年02月13日
    浏览(48)
  • Android权限申请库——EasyPermissions使用详解和打开相册方法

    1、添加依赖 2、在AndroidManifest文件中添加需要的权限 3、复写onRequestPermissionsResult方法 4、检查权限 5、申请权限 6、实现EasyPermissions.PermissionCallbacks接口,处理申请结果

    2024年02月15日
    浏览(47)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包