Android M 之权限管理

之所以写这篇文章,是要感谢昨天面试的时候面试官问到的权限相关的问题。自6.0之后权限系统被重新设计,发生了意想不到的变化,由之前只需在 Manifest 中注册,转化为一些涉及到用户隐私性的权限需动态授权。

借这次面试被打击的机会,学习一下权限动态管理的知识。特别感谢 ** duboo ** 的博客。http://www.cnblogs.com/dubo-/p/6018262.html。 推荐 duboo GitHub 示例。

  • 1、将 targetSdkVersion 设置为 23之上,如果低于 23 则不支持动态权限申请,否则必须按照Android谷歌的要求动态地申请权限。
  • 2、在 AndroidManifest.xml 中申请你需要的权限,包括普通权限和需要申请的特殊权限。

危险权限

  • group:android.permission-group.CONTACTS(联系人)

    • permission:android.permission.WRITE_CONTACTS
    • permission:android.permission.GET_ACCOUNTS
    • permission:android.permission.READ_CONTACTS
  • group:android.permission-group.PHONE(电话)

    • permission:android.permission.READ_CALL_LOG
    • permission:android.permission.READ_PHONE_STATE
    • permission:android.permission.CALL_PHONE
    • permission:android.permission.WRITE_CALL_LOG
    • permission:android.permission.USE_SIP
    • permission:android.permission.PROCESS_OUTGOING_CALLS
    • permission:com.android.voicemail.permission.ADD_VOICEMAIL
  • group:android.permission-group.CALENDAR(日历)

    • permission:android.permission.READ_CALENDAR
    • permission:android.permission.WRITE_CALENDAR
  • group:android.permission-group.CAMERA(相机)

    • permission:android.permission.CAMERA
  • group:android.permission-group.SENSORS(传感器)

    • permission:android.permission.BODY_SENSORS
  • group:android.permission-group.LOCATION(位置)

    • permission:android.permission.ACCESS_FINE_LOCATION
    • permission:android.permission.ACCESS_COARSE_LOCATION
  • group:android.permission-group.STORAGE(存储卡)

    • permission:android.permission.READ_EXTERNAL_STORAGE
    • permission:android.permission.WRITE_EXTERNAL_STORAGE
  • group:android.permission-group.MICROPHONE(麦克风)

    • permission:android.permission.RECORD_AUDIO
  • group:android.permission-group.SMS(短信)

    • permission:android.permission.READ_SMS
    • permission:android.permission.RECEIVE_WAP_PUSH
    • permission:android.permission.RECEIVE_MMS
    • permission:android.permission.RECEIVE_SMS
    • permission:android.permission.SEND_SMS
    • permission:android.permission.READ_CELL_BROADCASTS
  • 3、权限动态处理

    • 第一步:在 AndroidManifest 中,添加权限。举个栗子:录音和修改音量




* 第二步:检测权限类
/**
 * 权限检查工具类
 * Created by zsf on 17-4-15.
 */
public class PermissionsChecker {

    private Context mCtx;

    public PermissionsChecker(Context context){
        mCtx = context.getApplicationContext();
    }

    //判断权限集合
    public boolean lacksPermissions(String... permissions){
        for(String permission : permissions){
            if(lacksPermission(permission)){
                return true;
            }
        }
        return false;
    }

    //判断是否缺少权限
    public boolean lacksPermission(String permission){
        return ContextCompat.checkSelfPermission(mCtx,permission) == PackageManager.PERMISSION_DENIED;
    }
}
* 第三步:假设首页需要使用权限,在onResume时,检测权限,如果缺少,则进入权限获取页面;接收返回值,拒绝权限时,直接关闭。
public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 0; // 请求码

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.MODIFY_AUDIO_SETTINGS
    };

    @Bind(R.id.main_t_toolbar) Toolbar mTToolbar;

    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        setSupportActionBar(mTToolbar);

        mPermissionsChecker = new PermissionsChecker(this);
    }

    @Override protected void onResume() {
        super.onResume();

        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            startPermissionsActivity();
        }
    }

    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_CODE, PERMISSIONS);
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            finish();
        }
    }
}
* 第四步:授权页,首先使用系统默认的授权页没,当用户拒绝时,指导用户手动设置,当用户再次操作失败后,返回继续提示,用户手动退出授权页时,给使用页发送授权失败的通知。
/**
 * 权限获取页面
 * Created by zsf on 17-4-15.
 */
public class PermissionsActivity extends BaseActivity {
    public static final int PERMISSION_GRANTED = 0;//授权
    public static final int PERMISSION_DENIED = 1;//拒绝
    private static final int PERMISSION_REQUEST_CODE = 0;//系统权限管理页面的参数
    private static final String EXTRA_PERMISSIONS = "com.sanji.sjmallapp.permission.extra_permission";//权限参数
    private static final String PACKAGE_URL_SCHEME = "package:";
    private PermissionsChecker mChecker;//权限检测器
    private boolean isRequireCheck;//是否需要系统权限检测
    //启动但前权限页面的公开接口
    public static void startActivityForResult(Activity activity,int requestCode,String... permissions){
        Intent intent = new Intent(activity,PermissionsActivity.class);
        intent.putExtra(EXTRA_PERMISSIONS,permissions);
        ActivityCompat.startActivityForResult(activity,intent,requestCode,null);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getIntent() == null || !getIntent().hasExtra(EXTRA_PERMISSIONS)){
            throw new RuntimeException("PermissionsActivity需要使用静态startActivityForResult方法启动");
        }
        setContentView(R.layout.activity_permissions);
        mChecker = new PermissionsChecker(this);
        isRequireCheck = true;
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (isRequireCheck){
            String[] permissions = getPermissions();
            if (mChecker.lacksPermissions(permissions)){
                requestPermissions(permissions);// 请求权限
            }else{
                allPermissionsGranted();
            }
        }else{
            isRequireCheck = true;
        }
    }
    // 返回传递的权限参数
    private String[] getPermissions(){
        return getIntent().getStringArrayExtra(EXTRA_PERMISSIONS);
    }
    //请求权限兼容低版本
    private void requestPermissions(String... permissions){
        ActivityCompat.requestPermissions(this,permissions,PERMISSION_REQUEST_CODE);
    }
    //全部权限均已获取
    private void allPermissionsGranted(){
        setResult(PERMISSION_GRANTED);
        finish();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)){
            isRequireCheck = true;
            allPermissionsGranted();
        }else{
            isRequireCheck = false;
            showMissingPermissionDialog();
        }
    }
    //含有全部的权限
    private boolean hasAllPermissionsGranted(@NonNull int[] grantResults){
        for (int grantResult : grantResults){
            if (grantResult == PackageManager.PERMISSION_DENIED){
                return false;
            }
        }
        return true;
    }
    //显示缺失权限提示
    private void showMissingPermissionDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(PermissionsActivity.this);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);
        builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                setResult(PERMISSION_DENIED);
                finishActivity();
            }
        });
        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                startAppSettings();
            }
        });
        builder.show();
    }
    // 启动应用的设置
    private void startAppSettings(){
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }
}

下面看一下效果


Android M 之权限管理_第1张图片
权限引导图

你可能感兴趣的:(Android M 之权限管理)