Android版本升到6.0后最坑的就是权限问题,以下是我参考大神一个权限管理工具类,希望对大家有用

PermissionUtils.java

 import android.Manifest;
import android.app.Activity;
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.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast; import com.qicloud.fathercook.R; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* 类说明:权限工具
* copy from https://github.com/qianxiaoai/RuntimePermissionsDemo/tree/dev
* Author: Kuzan
* Date: 2016/12/15 16:44.
*/
public class PermissionUtils {
private static final String TAG = PermissionUtils.class.getSimpleName();
public static final int CODE_RECORD_AUDIO = 0;
public static final int CODE_GET_ACCOUNTS = 1;
public static final int CODE_READ_PHONE_STATE = 2;
public static final int CODE_CALL_PHONE = 3;
public static final int CODE_CAMERA = 4;
public static final int CODE_ACCESS_FINE_LOCATION = 5;
public static final int CODE_ACCESS_COARSE_LOCATION = 6;
public static final int CODE_READ_EXTERNAL_STORAGE = 7;
public static final int CODE_WRITE_EXTERNAL_STORAGE = 8;
public static final int CODE_CHANGE_CONFIGURATION = 9;
public static final int CODE_MULTI_PERMISSION = 100; public static final String PERMISSION_RECORD_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;
public static final String PERMISSION_CHANGE_CONFIGURATION = Manifest.permission.CHANGE_CONFIGURATION; private static final String[] requestPermissions = {
PERMISSION_RECORD_AUDIO, // 直接使用麦克风录制音频
PERMISSION_READ_PHONE_STATE, // 读取设备状态信息
PERMISSION_CALL_PHONE, // 拨打电话和管理电话
PERMISSION_CAMERA, // 直接使用相机以拍摄图片或视频
PERMISSION_READ_EXTERNAL_STORAGE, // 访问SD卡
PERMISSION_WRITE_EXTERNAL_STORAGE, // 操作SD卡
PERMISSION_ACCESS_FINE_LOCATION
}; public interface PermissionGrant {
void onPermissionGranted(int requestCode);
} /**
* Requests permission.
*
* @param activity
* @param requestCode request code, e.g. if you need request CAMERA permission,parameters is PermissionUtils.CODE_CAMERA
*/
public static void requestPermission(final Activity activity, final int requestCode, PermissionGrant permissionGrant) {
if (activity == null) {
return;
} Log.i(TAG, "requestPermission requestCode:" + requestCode);
if (requestCode < 0 || requestCode >= requestPermissions.length) {
Log.w(TAG, "requestPermission illegal requestCode:" + requestCode);
return;
} final String requestPermission = requestPermissions[requestCode]; //如果是6.0以下的手机,ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED,
// 但是,如果用户关闭了你申请的权限,ActivityCompat.checkSelfPermission(),会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null),
// 你可以使用try{}catch(){},处理异常,也可以判断系统版本,低于23就不申请权限,直接做你想做的。permissionGrant.onPermissionGranted(requestCode);
// if (Build.VERSION.SDK_INT < 23) {
// permissionGrant.onPermissionGranted(requestCode);
// return;
// } int checkSelfPermission;
try {
checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
} catch (RuntimeException e) {
Toast.makeText(activity, "please open this permission", Toast.LENGTH_SHORT)
.show();
Log.e(TAG, "RuntimeException:" + e.getMessage());
return;
} if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED"); if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
Log.i(TAG, "requestPermission shouldShowRequestPermissionRationale");
shouldShowRationale(activity, requestCode, requestPermission); } else {
Log.d(TAG, "requestCameraPermission else");
ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);
} } else {
Log.d(TAG, "ActivityCompat.checkSelfPermission ==== PackageManager.PERMISSION_GRANTED");
Toast.makeText(activity, "opened:" + requestPermissions[requestCode], Toast.LENGTH_SHORT).show();
permissionGrant.onPermissionGranted(requestCode);
}
} private static void requestMultiResult(Activity activity, String[] permissions, int[] grantResults, PermissionGrant permissionGrant) {
if (activity == null) {
return;
} //TODO
Log.d(TAG, "onRequestPermissionsResult permissions length:" + permissions.length);
Map<String, Integer> perms = new HashMap<>(); ArrayList<String> notGranted = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
Log.d(TAG, "permissions: [i]:" + i + ", permissions[i]" + permissions[i] + ",grantResults[i]:" + grantResults[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 success" + notGranted, Toast.LENGTH_SHORT)
// .show();
Log.e(TAG, "all permission success" + notGranted);
permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION);
} else {
openSettingActivity(activity, "those permission need granted!");
} } /**
* 一次申请多个权限
*/
public static void requestMultiPermissions(final Activity activity, PermissionGrant grant) { final List<String> permissionsList = getNoGrantedPermission(activity, false);
final List<String> shouldRationalePermissionsList = getNoGrantedPermission(activity, true); //TODO checkSelfPermission
if (permissionsList == null || shouldRationalePermissionsList == null) {
return;
}
Log.d(TAG, "requestMultiPermissions permissionsList:" + permissionsList.size() + ",shouldRationalePermissionsList:" + shouldRationalePermissionsList.size()); if (permissionsList.size() > 0) {
ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]),
CODE_MULTI_PERMISSION);
Log.d(TAG, "showMessageOKCancel requestPermissions"); } else if (shouldRationalePermissionsList.size() > 0) {
showMessageOKCancel(activity, "should open those permission",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),
CODE_MULTI_PERMISSION);
Log.d(TAG, "showMessageOKCancel requestPermissions");
}
});
} else {
grant.onPermissionGranted(CODE_MULTI_PERMISSION);
}
} private static void shouldShowRationale(final Activity activity, final int requestCode, final String requestPermission) {
//TODO
String[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);
showMessageOKCancel(activity, "Rationale: " + permissionsHint[requestCode], new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity,
new String[]{requestPermission},
requestCode);
Log.d(TAG, "showMessageOKCancel requestPermissions:" + requestPermission);
}
});
} private static void showMessageOKCancel(final Activity context, String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show(); } /**
* @param activity
* @param requestCode Need consistent with requestPermission
* @param permissions
* @param grantResults
*/
public static void requestPermissionsResult(final Activity activity, final int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults, PermissionGrant permissionGrant) { if (activity == null) {
return;
}
Log.d(TAG, "requestPermissionsResult requestCode:" + requestCode); if (requestCode == CODE_MULTI_PERMISSION) {
requestMultiResult(activity, permissions, grantResults, permissionGrant);
return;
} if (requestCode < 0 || requestCode >= requestPermissions.length) {
Log.w(TAG, "requestPermissionsResult illegal requestCode:" + requestCode);
Toast.makeText(activity, "illegal requestCode:" + requestCode, Toast.LENGTH_SHORT).show();
return;
} Log.i(TAG, "onRequestPermissionsResult requestCode:" + requestCode + ",permissions:" + permissions.toString()
+ ",grantResults:" + grantResults.toString() + ",length:" + grantResults.length); if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "onRequestPermissionsResult PERMISSION_GRANTED");
//TODO success, do something, can use callback
permissionGrant.onPermissionGranted(requestCode); } else {
//TODO hint user this permission function
Log.i(TAG, "onRequestPermissionsResult PERMISSION NOT GRANTED");
//TODO
String[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);
openSettingActivity(activity, "Result" + permissionsHint[requestCode]);
} } private static void openSettingActivity(final Activity activity, String message) { showMessageOKCancel(activity, message, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Log.d(TAG, "getPackageName(): " + activity.getPackageName());
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivity(intent);
}
});
} /**
* @param activity
* @param isShouldRationale true: return no granted and shouldShowRequestPermissionRationale permissions, false:return no granted and !shouldShowRequestPermissionRationale
* @return
*/
public 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]; //TODO checkSelfPermission
int checkSelfPermission = -1;
try {
checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
} catch (RuntimeException e) {
Toast.makeText(activity, "please open those permission", Toast.LENGTH_SHORT)
.show();
Log.e(TAG, "RuntimeException:" + e.getMessage());
return null;
} if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "getNoGrantedPermission ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED:" + requestPermission); if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
Log.d(TAG, "shouldShowRequestPermissionRationale if");
if (isShouldRationale) {
permissions.add(requestPermission);
} } else { if (!isShouldRationale) {
permissions.add(requestPermission);
}
Log.d(TAG, "shouldShowRequestPermissionRationale else");
} }
} return permissions;
}
}

在Activity中调用如下

 /**
* 判断是否有获取手机信息权限
*/
private boolean readPhoneStatePermission() {
int hasReadPhoneStatePermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE);
if (hasReadPhoneStatePermission == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
} @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
for (int i=0; i<permissions.length; i++) {
if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE)
&& grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// 用户同意获取手机信息权限
break;
}
}
PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
}
 private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
@Override
public void onPermissionGranted(int requestCode) {
switch (requestCode) {
case PermissionUtils.CODE_RECORD_AUDIO:
Log.w("Permission", "Result Permission Grant CODE_RECORD_AUDIO");
break;
case PermissionUtils.CODE_READ_PHONE_STATE:
Log.w("Permission", "Result Permission Grant CODE_READ_PHONE_STATE");
break;
case PermissionUtils.CODE_CALL_PHONE:
Log.w("Permission", "Result Permission Grant CODE_CALL_PHONE");
break;
case PermissionUtils.CODE_CAMERA:
Log.w("Permission", "Result Permission Grant CODE_CAMERA");
break;
case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
Log.w("Permission", "Result Permission Grant CODE_READ_EXTERNAL_STORAGE");
break;
case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
Log.w("Permission", "Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE");
break;
case PermissionUtils.CODE_MULTI_PERMISSION:
Log.w("Permission", "Result All Permission Grant");
break;
default:
break;
}
}
};

在onCreate中调用

PermissionUtils.requestMultiPermissions(this, mPermissionGrant);

判断是否有权限

if (readPhoneStatePermission()) {
// ToDo
}

android 6.0获取权限的更多相关文章

  1. Android 6.0的权限问题

    Android 6.0的权限获取不同于别的版本,具体的实例如下: if (ContextCompat.checkSelfPermission(this, Manifest.permission.REA ...

  2. Android开发之深入理解Android 7.0系统权限更改相关文档

    http://www.cnblogs.com/dazhao/p/6547811.html 摘要: Android 6.0之后的版本增加了运行时权限,应用程序在执行每个需要系统权限的功能时,需要添加权限 ...

  3. 解决Android 6.0获取wifi Mac地址为02:00:00:00:00:00问题【转】

    本文转载自:http://www.jb51.net/article/128398.htm 这篇文章主要介绍了Android 6.0获取wifi Mac地址为02:00:00:00:00:00的解决方法 ...

  4. Android 6.0 - 动态权限管理的解决方案(转)

    转自:http://www.cnblogs.com/dubo-/p/6018262.html Android 6.0 - 动态权限管理的解决方案   转载请标注 Android 6.0版本(Api 2 ...

  5. android 6.0+ 动态权限 拒绝不再询问后跳转设置应用详情页面

    android 6.0+ 的权限 需要动态申请 这里的权限针对的是 敏感权限: SMS(短信) SEND_SMS RECEIVE_SMS READ_SMS RECEIVE_WAP_PUSH RECEI ...

  6. android 6.0 动态权限

    Android 6.0 动态权限: 除了要在AndroidManifest.xml中申请外,还需使用时,请求用户允许授权. 以下是需要单独申请的权限,共分为9组,每组只要有一个权限申请成功了,就默认整 ...

  7. Android 6.0动态权限申请

    转载(Android 6.0 动态权限申请简单简洁优雅的处理方式): https://blog.csdn.net/lin_dianwei/article/details/79025324

  8. android 6.0获取 WRITE_SETTINGS 权限

    android 6.0上只写在AndroidManifest中是不行的,还必须手动打开才行 private void setBrightnessMode(Context context, int mo ...

  9. Android 6.0 - 动态权限管理的解决方案

    Android 6.0版本(Api 23)推出了很多新的特性, 大幅提升了用户体验, 同时也为程序员带来新的负担. 动态权限管理就是这样, 一方面让用户更加容易的控制自己的隐私, 一方面需要重新适配应 ...

随机推荐

  1. linq中的分组和排序

    一.分组  group 组内成员 by 分组条件 into 组的信息 class Program { static void Main(string[] args) { string[] name = ...

  2. 字符串查找 cmd find命令

    find /i "ora-" *.log 我对findstr是如此的依赖,以至于当我向各位讲解find命令的时候,我还得老老实实地在cmd窗口中敲下 find /? 这条命令,然后 ...

  3. 转 Oracle 12c 使用scott等普通用户的方法

    一.前言 最近电脑上安装了oracle 12c数据库,想体验下新特性.安装完后,便像11g一样在dos窗口进行下面的操作: SQL*Plus: Release 12.1.0.2.0 Productio ...

  4. 【servlet】 过滤器模板

    EncodingFilter.java package Filter; import java.io.IOException; import javax.servlet.Filter; import ...

  5. json对象的简单介绍

    1.JSON(JavaScript Object Notation)一种简单的数据格式,比xml更轻巧.JSON是JavaScript原生格式,这意味着在JavaScript中处理JSON数据不需要任 ...

  6. JSP中文编码问题

    这个乱码问题是最简单的乱码问题.一般新会出现.就是页面编码不一致导致的乱码. <%@ page language="java" pageEncoding="UTF- ...

  7. KNN邻近分类算法

    K邻近(k-Nearest Neighbor,KNN)分类算法是最简单的机器学习算法了.它采用测量不同特征值之间的距离方法进行分类.它的思想很简单:计算一个点A与其他所有点之间的距离,取出与该点最近的 ...

  8. L3,please send me a card

    expressions: a few words几句话 lend sb sth或lend sth to sb borrow sth或borrow sth from sb 都表示借,但是行为不同. wo ...

  9. Spring注解基本解读

    在一个类中使用Spring对象,办法如下: 使用注解的形式注入 从ApplicationContext中获取. T t = new ApplicationContext.getBean("x ...

  10. jq中的css-Dom

    1,height() ,width() 此方法用来获取匹配元素的高和宽的值,如果括号内有值,则是修改匹配元素的值, 2.offset() 此方法的作用是获取元素在当前视窗的相对偏移,其中返回的对象包含 ...