Android 6.0 动态权限申请实例

首先,在AndrodManifest.xml文件中写入权限。

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

然后在MainActivity.java文件中对Android6.0以上的系统进行权限申请。

package com.zhaoxin.mypermissionstest;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

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

/**
 * android6.0以上申请权限
 */
public class MainActivity extends AppCompatActivity {

    // 未授予的权限集合
    private List requestPermissions;
    // 请求权限时的请求码
    private static final int REQUEST_CODE = 1;

    // 申请权限相关
    private static String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (checkPermission()) {// 检测权限已全部授予
            // 下一步
            next();
        } else {
            // 请求权限
            ActivityCompat.requestPermissions(this, requestPermissions.toArray(new String[requestPermissions.size()]), REQUEST_CODE);
        }
    }

    /**
     * 检查权限
     *
     * @return 是否已全部授权
     */
    private boolean checkPermission() {

        // 权限是否授予标志位
        boolean isPermissionGranted = true;
        requestPermissions = new ArrayList<>();
        // 检查权限是否授予
        if (ContextCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(permissions[0]);
            isPermissionGranted = false;
        }
        if (ContextCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(permissions[1]);
            isPermissionGranted = false;
        }
        if (ContextCompat.checkSelfPermission(this, permissions[2]) == PackageManager.PERMISSION_DENIED) {
            requestPermissions.add(permissions[2]);
            isPermissionGranted = false;
        }
        return isPermissionGranted;
    }

    /**
     * 处理请求结果
     *
     * @param requestCode  请求码
     * @param permissions  权限集合
     * @param grantResults 授权结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE:
                boolean isAllGranted = true;
                // 遍历授权结果,一旦检测到未授权,则将isAllGranted置为false,并跳出循环
                for (int grantResult : grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        isAllGranted = false;
                        break;
                    }
                }
                if (isAllGranted)
                    // 全部授权通过则进入下一步
                    next();
                else
                    // 否则引导用户手动授权 
                    openAppDetails();
                break;
            default:
                break;
        }
    }

    /**
     * 申请权限成功后要做的事
     */
    private void next() {
        Toast.makeText(this, "申请权限成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 打开应用的详情设置
     */
    private void openAppDetails() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("该应用需要访问 “相机” 和 “外部存储器”,请到 “应用 -> 权限” 中授予!");
        builder.setPositiveButton("去手动授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }
}

你可能感兴趣的:(Android)