android 权限问题

6.0 Android引入动态权限,如果sdk指定targetSdkVersion > 23 那你应用运行使用的权限静态写入的就不够用了。要动态申请 否则就要报错,
一般用的权限有,sd卡读写(相册)、相机、音频、蓝牙、位置、拨号等等。
注意:一般相册只用的读的权限,如果只申请了读的权限,那么写的时候会出错,但是你查看权限的时候显示的是读写权限已被允许,以免造成干扰,所以最好是sd卡相关权限就一起申请

 ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE_ASK_STORAGE_PERMISSIONS);

权限申请栗子:

package com.ihealth.chronos.patient.control.permission;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
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.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ihealth.chronos.patient.R;
import com.ihealth.chronos.patient.common.BasicActivity;
import com.ihealth.chronos.patient.util.LogUtil;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
* Created by huo on 2016/7/6.
* 权限管理
*/
public class PermissionManager {

   public static final int REQUEST_CODE_ASK_CAMERA_PERMISSIONS = 101;//申请相机
   public static final int REQUEST_CODE_ASK_STORAGE_PERMISSIONS = 102;//申请存储
   public static final int REQUEST_CODE_ASK_AUDIO_PERMISSIONS = 103;//申请音频
   public static final int REQUEST_CODE_ASK_AUDIO_MEASURE_PERMISSIONS = 104;//申请测量音频
   public static final int REQUEST_CODE_ASK_PHONE_PERMISSIONS = 105;//申请电话
   public static final int REQUEST_CODE_ASK_BlUETOOTH_PERMISSIONS = 106;//申请蓝牙
   public static final String SETTINGS_ACTION =
           "android.settings.APPLICATION_DETAILS_SETTINGS";
   public static final int WHAT_PER_MESSAGE = 0;//问医申请语音权限
   public static int what = -1;//标识检测权限的动作

   /***
    * 检测相册
    */
   public static boolean checkPhotoAlbum(Activity activity) {
       return checkPhotoAlbum(activity,-1);
   }

   /***
    * 检测相册
    */
   public static boolean checkPhotoAlbum(Activity activity,int whatTemp) {
       what = whatTemp;
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasReadStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.READ_EXTERNAL_STORAGE);
       int hasWriteStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.WRITE_EXTERNAL_STORAGE);
       LogUtil.v("Permission  PermissionManager checkPhotoAlbum hasWriteStoragePermission = ",hasWriteStoragePermission,"  hasReadStoragePermission = ",hasReadStoragePermission);
       if (hasReadStoragePermission != PackageManager.PERMISSION_GRANTED || hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
           ActivityCompat.requestPermissions(activity,
                   new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                   REQUEST_CODE_ASK_STORAGE_PERMISSIONS);
           return false;
       }
       return true;
   }

   /***
    * 检测相册
    */
   public static boolean checkPhotoAlbum(Activity activity,Fragment fragment) {
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasReadStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.READ_EXTERNAL_STORAGE);
       int hasWriteStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.WRITE_EXTERNAL_STORAGE);
       LogUtil.v("Permission  PermissionManager checkPhotoAlbum hasWriteStoragePermission = ",hasWriteStoragePermission,"  hasReadStoragePermission = ",hasReadStoragePermission);
       if (hasReadStoragePermission != PackageManager.PERMISSION_GRANTED || hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
           if (!fragment.shouldShowRequestPermissionRationale(
                   Manifest.permission.READ_EXTERNAL_STORAGE)) {
               fragment.requestPermissions(
                       new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                       REQUEST_CODE_ASK_STORAGE_PERMISSIONS);
               return false;
           }
           fragment.requestPermissions(
                   new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                   REQUEST_CODE_ASK_STORAGE_PERMISSIONS);
           return false;
       }
       return true;
   }


   /***
    * 检测相册
    */
   public static boolean checkPhone(Activity activity,int whatTemp) {
       what = whatTemp;
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.READ_PHONE_STATE);
       LogUtil.v("Permission  PermissionManager checkPhotoAlbum hasStoragePermission = ",hasStoragePermission,"  hasStoragePermission = ",hasStoragePermission);
       if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
           ActivityCompat.requestPermissions(activity,
                   new String[]{Manifest.permission.READ_PHONE_STATE},
                   REQUEST_CODE_ASK_PHONE_PERMISSIONS);
           return false;
       }
       return true;
   }

   /***
    * 检测相机
    */
   public static boolean checkCamera(Activity activity) {
       return checkCamera(activity,-1);
   }

   /***
    * 检测相机
    */
   private static boolean checkCamera(Activity activity,int whatTemp) {
       what = whatTemp;
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasCameraPermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.CAMERA);
       int hasReadStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.READ_EXTERNAL_STORAGE);
       int hasWriteStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.WRITE_EXTERNAL_STORAGE);
       LogUtil.v("Permission  PermissionManager checkCamera hasCameraPermission = ",hasCameraPermission,"  hasStoragePermission = ",hasReadStoragePermission,"  hasWriteStoragePermission = ",hasWriteStoragePermission);
       if (hasCameraPermission != PackageManager.PERMISSION_GRANTED || hasReadStoragePermission != PackageManager.PERMISSION_GRANTED || hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
           ActivityCompat.requestPermissions(activity,
                       new String[]{Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                       REQUEST_CODE_ASK_CAMERA_PERMISSIONS);
           return false;
       }
       return true;
   }

   /***
    * 检测相机
    */
   public static boolean checkCameraOnly(Activity activity) {
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasCameraPermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.CAMERA);
       LogUtil.v("Permission  PermissionManager checkCamera hasCameraPermission = ",hasCameraPermission);
       if(hasCameraPermission != PackageManager.PERMISSION_GRANTED){
           ActivityCompat.requestPermissions(activity,
                   new String[]{Manifest.permission.CAMERA},
                   REQUEST_CODE_ASK_CAMERA_PERMISSIONS);
           return false;
       }
       return true;
   }

   /***
    * 检测音频
    */
   public static boolean checkAudio(Activity activity) {
      return checkAudio(activity,-1);
   }

   /***
    * 检测音频
    */
   public static boolean checkAudio(Activity activity,int whatTemp) {
       what = whatTemp;
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasAudioPermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.RECORD_AUDIO);
       int hasReadStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.READ_EXTERNAL_STORAGE);
       int hasWriteStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.WRITE_EXTERNAL_STORAGE);
       LogUtil.v("Permission  PermissionManager checkAudio hasAudioPermission = ",hasAudioPermission,"  hasWriteStoragePermission = ",hasWriteStoragePermission,"  hasReadStoragePermission = ",hasReadStoragePermission);
       if (hasAudioPermission != PackageManager.PERMISSION_GRANTED || hasReadStoragePermission != PackageManager.PERMISSION_GRANTED|| hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
           ActivityCompat.requestPermissions(activity,
                   new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                   REQUEST_CODE_ASK_AUDIO_PERMISSIONS);
           return false;
       }
       return true;
   }

   /***
    * 检测血压蓝牙相关权限
    */
   public static boolean checkBluetoothMeasure(Activity activity) {
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasReadStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.READ_EXTERNAL_STORAGE);
       int hasWriteStoragePermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.WRITE_EXTERNAL_STORAGE);
       int hasAudioPermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.RECORD_AUDIO);
       int hasLocationPermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.ACCESS_FINE_LOCATION);
       if (hasReadStoragePermission != PackageManager.PERMISSION_GRANTED || hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED || hasAudioPermission != PackageManager.PERMISSION_GRANTED
               || hasLocationPermission != PackageManager.PERMISSION_GRANTED) {
               ActivityCompat.requestPermissions(activity,
                       new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO,Manifest.permission.ACCESS_FINE_LOCATION},
                       REQUEST_CODE_ASK_BlUETOOTH_PERMISSIONS);
           return false;
       }
       return true;
   }


   /***
    * 检测音频
    */
   public static boolean checkAudioMeasure(Activity activity) {
       if (Build.VERSION.SDK_INT < 23) {
           return true;
       }
       int hasAudioPermission = ContextCompat.checkSelfPermission(activity,
               Manifest.permission.RECORD_AUDIO);
       if (hasAudioPermission != PackageManager.PERMISSION_GRANTED ) {//|| hasStoragePermission != PackageManager.PERMISSION_GRANTED
           ActivityCompat.requestPermissions(activity,
                   new String[]{Manifest.permission.RECORD_AUDIO},//,Manifest.permission.READ_EXTERNAL_STORAGE
                   REQUEST_CODE_ASK_AUDIO_MEASURE_PERMISSIONS);
           return false;
       }
       return true;
   }

   /***
    * 是否允许权限
    * @param grantResults
    * @param activity
    * @return
    */
   public static boolean isPermitPermissions(@NonNull int[] grantResults, final Activity activity,int code) {
       for (int state : grantResults){
           if (state != PackageManager.PERMISSION_GRANTED){
               if (!activity.isFinishing()){
                   MaterialDialog.Builder builder = new MaterialDialog.Builder(activity).autoDismiss(false)
                           .negativeColorRes(R.color.predefine_color_assist_red)
                           .onNegative(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                   dialog.dismiss();
                               }
                           }).title(R.string.txt_permission_require_title).content(getPermissionsPrompt(code))
                           .positiveColorRes(R.color.predefine_font_important)
                           .onPositive(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                       dialog.dismiss();
                                   Intent intent = new Intent();
                                   intent.setAction(SETTINGS_ACTION);
                                   intent.setData(Uri.fromParts("package",activity.getPackageName(), null));
                                   activity.startActivity(intent);
                               }
                           }).negativeText(R.string.cancel).positiveText(R.string.txt_permission_go_set);
                   builder.show();
               }
               return false;
           }
       }
       return true;
   }

   /***
    * 是否允许权限
    * @param grantResults
    * @param activity
    * @return
    */
   public static boolean isPermitPermissionsAndForceFinish(@NonNull int[] grantResults, final Activity activity,int code) {
       for (int state : grantResults){
           if (state != PackageManager.PERMISSION_GRANTED){
               if (!activity.isFinishing()){
                   MaterialDialog.Builder builder = new MaterialDialog.Builder(activity).autoDismiss(false)
                           .negativeColorRes(R.color.predefine_color_assist_red)
                           .onNegative(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                   activity.finish();
                                   dialog.dismiss();
                               }
                           }).title(R.string.txt_permission_require_title).content(getPermissionsPrompt(code))
                           .positiveColorRes(R.color.predefine_font_important)
                           .onPositive(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                   dialog.dismiss();
                                   Intent intent = new Intent();
                                   intent.setAction(SETTINGS_ACTION);
                                   intent.setData(Uri.fromParts("package",activity.getPackageName(), null));
                                   activity.startActivity(intent);
                               }
                           }).negativeText(R.string.cancel).positiveText(R.string.txt_permission_go_set);
                   builder.show();
               }
               return false;
           }
       }
       return true;
   }

   /***
    * 是否允许权限
    * @param grantResults
    * @param activity
    * @return
    */
   public static boolean isPermitPermissionsAndForceFinishDouble(@NonNull int[] grantResults, final Activity activity,int code) {
       for (int state : grantResults){
           if (state != PackageManager.PERMISSION_GRANTED){
               if (!activity.isFinishing()){
                   MaterialDialog.Builder builder = new MaterialDialog.Builder(activity).autoDismiss(false)
                           .negativeColorRes(R.color.predefine_color_assist_red)
                           .onNegative(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                   activity.finish();
                                   dialog.dismiss();
                               }
                           }).title(R.string.txt_permission_require_title).content(getPermissionsPrompt(code))
                           .positiveColorRes(R.color.predefine_font_important)
                           .onPositive(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                   dialog.dismiss();
                                   activity.finish();
                                   Intent intent = new Intent();
                                   intent.setAction(SETTINGS_ACTION);
                                   intent.setData(Uri.fromParts("package",activity.getPackageName(), null));
                                   activity.startActivity(intent);
                               }
                           }).negativeText(R.string.cancel).positiveText(R.string.txt_permission_go_set);
                   builder.show();
               }
               return false;
           }
       }
       return true;
   }
   /***
    * 是否允许权限 点击取消不finish
    * @param grantResults
    * @param activity
    * @return
    */
   public static boolean isPermitPermissionsAndForceNoFinishDouble(@NonNull int[] grantResults, final Activity activity,int code) {
       for (int state : grantResults){
           if (state != PackageManager.PERMISSION_GRANTED){
               if (!activity.isFinishing()){
                   MaterialDialog.Builder builder = new MaterialDialog.Builder(activity).autoDismiss(false)
                           .negativeColorRes(R.color.predefine_color_assist_red)
                           .onNegative(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                    activity.finish();
                                   dialog.dismiss();
                               }
                           }).title(R.string.txt_permission_require_title).content(getPermissionsPrompt(code))
                           .positiveColorRes(R.color.predefine_font_important)
                           .onPositive(new MaterialDialog.SingleButtonCallback() {
                               @Override
                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                   dialog.dismiss();
//                                    activity.finish();
                                   Intent intent = new Intent();
                                   intent.setAction(SETTINGS_ACTION);
                                   intent.setData(Uri.fromParts("package",activity.getPackageName(), null));
                                   activity.startActivity(intent);
                               }
                           }).negativeText(R.string.cancel).positiveText(R.string.txt_permission_go_set);
                   builder.show();
               }
               return false;
           }
       }
       return true;
   }

   private static int getPermissionsPrompt(int code){
       switch (code){
           case REQUEST_CODE_ASK_CAMERA_PERMISSIONS:
               return R.string.txt_permission_require_camera;
           case REQUEST_CODE_ASK_STORAGE_PERMISSIONS:
               return R.string.txt_permission_require_storage;
           case REQUEST_CODE_ASK_AUDIO_PERMISSIONS:
           case REQUEST_CODE_ASK_AUDIO_MEASURE_PERMISSIONS:
               return R.string.txt_permission_require_audio;
           case REQUEST_CODE_ASK_PHONE_PERMISSIONS:
               return R.string.txt_permission_require_phone;
           case REQUEST_CODE_ASK_BlUETOOTH_PERMISSIONS:
               return R.string.txt_permission_require_bluetooth;
       }
       return 0;
   }

   private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
   private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

   /**
    * 检测通知权限
    * @param context
    * @return
    */
   @SuppressLint("NewApi")
   public static boolean checkNotificationEnabled(final BasicActivity context) {
       boolean isEnabled;
       AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
       ApplicationInfo appInfo = context.getApplicationInfo();
       String pkg = context.getApplicationContext().getPackageName();
       int uid = appInfo.uid;

       Class appOpsClass = null;
     /* Context.APP_OPS_MANAGER */
       try {
           appOpsClass = Class.forName(AppOpsManager.class.getName());
           Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                   String.class);
           Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
           int value = (Integer) opPostNotificationValue.get(Integer.class);
           isEnabled =  ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
       } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException | InvocationTargetException | IllegalAccessException e) {
           isEnabled = true;
           e.printStackTrace();
       }

       if (!isEnabled){
           MaterialDialog.Builder builder = new MaterialDialog.Builder(context).autoDismiss(false)
                   .negativeColorRes(R.color.predefine_color_assist_red)
                   .onNegative(new MaterialDialog.SingleButtonCallback() {
                       @Override
                       public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                           dialog.dismiss();
                           context.finish();
                       }
                   }).content(R.string.txt_permission_require_notification)
                   .positiveColorRes(R.color.predefine_font_important)
                   .onPositive(new MaterialDialog.SingleButtonCallback() {
                       @Override
                       public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                           dialog.dismiss();
                           Intent intent = new Intent();
                           intent.setAction(SETTINGS_ACTION);
                           intent.setData(Uri.fromParts("package",context.getPackageName(), null));
                           context.startActivity(intent);
                       }
                   }).negativeText(R.string.non).positiveText(R.string.open_notifi);
           builder.show();
       }
       return isEnabled;
   }

   /**
    * 检测通知权限
    * @param context
    * @return
    */
   @SuppressLint("NewApi")
   public static boolean checkMedicationNotificationEnabled(final BasicActivity context) {
       boolean isEnabled;
       AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
       ApplicationInfo appInfo = context.getApplicationInfo();
       String pkg = context.getApplicationContext().getPackageName();
       int uid = appInfo.uid;

       Class appOpsClass = null;
     /* Context.APP_OPS_MANAGER */
       try {
           appOpsClass = Class.forName(AppOpsManager.class.getName());
           Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                   String.class);
           Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
           int value = (Integer) opPostNotificationValue.get(Integer.class);
           isEnabled =  ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
       } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException | InvocationTargetException | IllegalAccessException e) {
           isEnabled = true;
           e.printStackTrace();
       }
       return isEnabled;
   }
}

调用:相机相册

 if (PermissionManager.checkCamera(MyInfoActivity.this))
                            choosePhoto();

回调:相机相册

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PermissionManager.REQUEST_CODE_ASK_CAMERA_PERMISSIONS:
                if (PermissionManager.isPermitPermissions(grantResults,this,requestCode))
                    choosePhoto();
                break;
            case PermissionManager.REQUEST_CODE_ASK_STORAGE_PERMISSIONS:
                if (PermissionManager.isPermitPermissions(grantResults,this,requestCode))
                    handleSelectPicture();
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

你可能感兴趣的:(android 权限问题)