Android 权限动态申请

Android 6以后,权限需要动态申请,以下 是整理的动态申请权限的工具类,Android 7.0亲测可用,转载请载明出处:https://blog.csdn.net/sdbzmyh0/article/details/79947971

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018-03-16.
 */
public class PermissionUtil {
    //private String[] permissions={Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public static boolean CheckPermission(Activity activity, Context context, String PermissionRequest){
        int permission=-1;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permission = ContextCompat.checkSelfPermission(context, PermissionRequest);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{PermissionRequest}, 1);
            }
        }
        else {
            permission= PackageManager.PERMISSION_GRANTED;
        }
        return permission== PackageManager.PERMISSION_GRANTED;
    }
    public static boolean CheckPermissions(Activity activity, Context context, String[] PermissionRequests){
        boolean PermissionRequest=true;
        int permission=-1;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for(int i=0;i<PermissionRequests.length;i++) {
                permission = ContextCompat.checkSelfPermission(context, PermissionRequests[i]);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    PermissionRequest=false;
                    break;
                }
            }
        }
        return PermissionRequest;
    }
    public static void RequestPermission(Activity activity, Context context, String... PermissionRequest){
        int permission=-1;

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> listPermissions = new ArrayList<>();

            for (int i = 0; i < PermissionRequest.length; i++) {
                permission = ContextCompat.checkSelfPermission(context, PermissionRequest[i]);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    listPermissions.add(PermissionRequest[i]);
                }
            }
            String[] stringsPermissions=new String[listPermissions.size()];
            stringsPermissions=listPermissions.toArray(new String[listPermissions.size()]);
            if(stringsPermissions.length>0){
                activity.requestPermissions(stringsPermissions,1);
            }
        }
    }
}
邮箱:sdbzmyh@163.com,qq:279931514,微信:sdbzmyh
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页