/**
* 权限的验证及处理,相关方法
*/
private void getReadPermissions() {
Log.i("日志:权限", "检测权限 ");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED
| ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECEIVE_SMS) | ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {//是否请求过该权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 10001);
} else {//没有则请求获取权限,示例权限是:存储权限和短信权限,需要其他权限请更改或者替换
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10001);
}
} else {//如果已经获取到了权限则直接进行下一步操作
//启动SmsService
intentService = new Intent(this, SmsService.class);
startService(intentService);
Log.i("日志:开启服务", "启动SmsService: ");
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 10001:
for (int i = 0; i < grantResults.length; i++) {
// 如果拒绝获取权限
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
//判断是否勾选禁止后不再询问
boolean flag = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
if (flag) {
getReadPermissions();
return;//用户权限是一个一个的请求的,只要有拒绝,剩下的请求就可以停止,再次请求打开权限了
} else { // 勾选不再询问,并拒绝
Toast.makeText(this, "请到设置中打开权限", Toast.LENGTH_LONG).show();
return;
}
}
}
break;
default:
break;
}
}
android 监听手机短信-检测权限
最新推荐文章于 2024-10-16 19:58:12 发布