Android 6.0 向用户申请权限,运行时权限

Android 6.0权限分:普通权限和运行时权限
对于普通权限不用向用户申请只需要在manifest声明,运行时权限是涉及到用户隐私需要手动向用户申请不然会出现奔溃问题
public class MainActivity extends Activity {
    public final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 123;
    //添加多个权限
    public String[] permissions = new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

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

        if (!hasPermission(this)) {
            requestPermissions(permissions, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        } else {
            //用户已经授权或者版本在6.0以下
        }
    }

    /**  * 6.0获取权限  *  * @return  */  public boolean hasPermission(Context mContext) {
        boolean hasPermission = true;
        if (Build.VERSION.SDK_INT >= 23) {
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(mContext, permissions[i]) != PackageManager.PERMISSION_GRANTED) {//判断用户是否对添加的权限授权
                    //用户没有授权
                    hasPermission = false;
                    break;
                }
            }
        } else {
            hasPermission = true;
        }
        return hasPermission;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        boolean isOpen = true;
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {//判断添加的权限用户是否授权
                        isOpen = false;
                        break;
                    }
                }
                if (isOpen) {
                    // Android 6.0 用户已经授权 执行授权之后的操作
                } else {
                    // 执行用户没有授权的操作
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

你可能感兴趣的:(优化,android,控件,用户隐私)