1,添加权限标识用来判断当前APP是否已经拥有权限
/** 6.0权限处理 **/
private boolean bPermission = false;//权限标识
private final int WRITE_PERMISSION_REQ_CODE = 100;//请求码
2,申请授权
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/** 6.0权限申请 **/
bPermission = checkPublishPermission(); //activity打开时申请
}
3,请求授权
//请求权限示例
private boolean checkPublishPermission() {
if (Build.VERSION.SDK_INT >= 23) {
List<String> permissions = new ArrayList<>();
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(NEMainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//检查是否申请了文件写入权限,若果没有则添加到权限集合,下同
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(NEMainActivity.this, Manifest.permission.CAMERA)) {
permissions.add(Manifest.permission.CAMERA);
}
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(NEMainActivity.this, Manifest.permission.READ_PHONE_STATE)) {
permissions.add(Manifest.permission.READ_PHONE_STATE);
}
if (permissions.size() != 0) {
ActivityCompat.requestPermissions(NEMainActivity.this,//权限申请(上下文,权限清单,请求码)
(String[]) permissions.toArray(new String[0]),
WRITE_PERMISSION_REQ_CODE);
return false;
}
}
return true;
}
4,处理回调
//权限请求回调,如果集合中任意一个权限被拒绝了直接return,此时权限的flag为false,如果全部同意标识为true
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case WRITE_PERMISSION_REQ_CODE:
for (int ret : grantResults) {
if (ret != PackageManager.PERMISSION_GRANTED) {
return;
}
}
bPermission = true;
break;
default:
break;
}
}
5,更加权限flag做相应的处理
//调用需要申请权限的逻辑时检查是否已经有了权限如果没有则不允许操作,否则可能导致程序崩溃,并再次弹出授权窗口
if(!bPermission){
Toast.makeText(getApplication(),"请先允许app所需要的权限",Toast.LENGTH_LONG).show();
bPermission = checkPublishPermission();
return;
}else{//如果权限申请通过,执行正常的程序逻辑
执行逻辑...
}
本篇只是演示一个流程并不建议这样去处理权限,因为在程序启动的时候就去申请所有权限是非常愚蠢的也失去的动态权限的意义,而且在用户不知道为什么要使用这些权限的情况下很有可能拒绝权限的申请,而导致一堆问题