欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android 两种动态获权的方法?

程序员文章站 2022-04-12 22:17:16
一、自定义动态获权1.创建BaseActivity,将动态获权代码进行编写package com.ruidde.pictureselectordemo.base;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;...

一、自定义动态获权

1.创建BaseActivity,将动态获权代码进行编写

package com.ruidde.pictureselectordemo.base;

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 androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

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

/**
 * 动态获取权限的类
 */

public class BasePermissionsActivity extends AppCompatActivity {
    public String tag=getClass().getSimpleName();
    private int REQUEST_CODE_PERMISSION = 0x00099;
    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionSuccess(REQUEST_CODE_PERMISSION);
        } else {
            try {
                List<String> needPermissions = getDeniedPermissions(permissions);
                ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
            }catch (Exception e){
                Log.e("5555555", "获取权限try" + e);
            }

        }
    }
    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }
    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }

    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
            }
        }
    }
    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    /**
     * 显示提示对话框
     */
    protected void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限,该功能暂时无法使用。如若需要,请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }
    @Override
    public void startActivity(Intent intent) {
        // TODO Auto-generated method stub
        super.startActivity(intent);
    }
    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {
        Log.e(tag, "获取权限成功=" + requestCode);

    }

    /**
     * 权限获取失败
     * @param requestCode
     */
    public void permissionFail(int requestCode) {
        Log.e(tag, "获取权限失败=" + requestCode);
    }

}

2.在Activity中调用动态获权

package com.ruidde.pictureselectordemo;

import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ruidde.pictureselectordemo.base.BasePermissionsActivity;

public class MainActivity2 extends BasePermissionsActivity {
    private Context mContext;
    private TextView btnPerssion;

    private static final int PM_CAMERA_AND_CALL = 1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initData();
    }

    private void initData() {
        btnPerssion = findViewById(R.id.btnPerssion);

        btnPerssion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission(new String[]{
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.CAMERA
                }, PM_CAMERA_AND_CALL);
            }
        });
    }

    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case PM_CAMERA_AND_CALL:
                Toast.makeText(this, "已授权!", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        showTipsDialog();
        Toast.makeText(this, "未授权不可使用", Toast.LENGTH_SHORT).show();
    }
}

二、引用动态获权框架(easypermissions)

1.首先在项目的build中dependencies下添加

//动态权限框架(MainActivity)
implementation 'pub.devrel:easypermissions:2.0.1'

2.在Activity中调用

package com.ruidde.pictureselectordemo;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.content.ContentValues.TAG;

public class MainActivity extends Activity {
    private Context mContext;
    private TextView btnPerssion;

    private static final int PM_CAMERA_AND_WIFI = 1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initData();
    }

    private void initData() {
        btnPerssion = findViewById(R.id.btnPerssion);

        btnPerssion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodRequiresPermission();
            }
        });
    }

    @AfterPermissionGranted(PM_CAMERA_AND_WIFI)
    private void methodRequiresPermission() {
        //String[] perms = {Manifest.permission.CAMERA};
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.CALL_PHONE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            Toast.makeText(mContext, "权限授予成功!!!", Toast.LENGTH_SHORT).show();
        } else {
            EasyPermissions.requestPermissions(this,"没有权限,现在申请权限", PM_CAMERA_AND_WIFI, perms);
        }
    }

}

3.easypermissions框架元原链接:https://github.com/chenshouyin/EasyPermissions

 

4.整体的XML文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/btnPerssion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="40dp"
        android:background="@color/colorAccent"
        android:textColor="@color/main_nav_white"
        android:layout_marginTop="20dp"
        android:textSize="20sp"
        android:gravity="center"
        android:text="动态获权"/>

</RelativeLayout>

 

本文地址:https://blog.csdn.net/yyxhzdm/article/details/108716032