参考文章:
Android6.0运行时权限解析,RxPermissions的使用,自己封装一套权限框架
//正常获取权限
private void checkPermissionForNormal() {
//判断是否同意此权限
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//如果应用之前请求过此权限但用户拒绝了请求,此方法将返回 true
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CALL_PHONE)) {
Toast.makeText(this, "你之前拒绝过此权限", Toast.LENGTH_SHORT).show();
} else {
//申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 100);
}
} else {
callPhone();
}
}
//权限的回调
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 100: {
//返回的结果数组大于0说明有结果
if (grantResults.length > 0
//因为我们只判断了一个打电话的权限,所有是数组的0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "同意了权限", Toast.LENGTH_SHORT).show();
callPhone();
} else {
Toast.makeText(this, "拒绝了权限", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
RxPermission的使用
RxPermissions.getInstance(this).request(Manifest.permission.READ_CONTACTS)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
if (aBoolean) {
Calendar CD = Calendar.getInstance();
int YY = CD.get(Calendar.YEAR) ;
Toast.makeText(MainActivity.this,"获取成功"+YY,Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"获取失败",Toast.LENGTH_SHORT).show();
}
}
});