您的位置:首页 > 移动开发 > Android开发

Android 6.0改动之运行时权限

2016-06-07 00:16 411 查看
Android6.0给我们带来了新的特性和功能,同时也有值得开发者注意的地方 。这些改动包括了系统和api上面。本篇文档有几个关键点的改动需要我们注意。

第一,运行时权限。Android6.0版本接受了新的权限模型,这个使得用户现在可以直接在app运行过程中管理app的某些权限。例如授予和撤销某个权限。

一旦你的app运行在Android6.0以上时,你需要对你的app运行期间所需权限进行检查,防止app的crash。其中检查某一权限是否被授予可以调用int
checkSelfPermission (String permission)返回结果PERMISSION_GRANTED或者PERMISSION_DENIED;请求某一权限可以调用void
requestPermissions (String[] permissions, int requestCode),随后你必须重写这个在void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults)方法里接受结果,来判断用户是否授予了你的权限。以便控制后续app的逻辑。

下面针对app在Android6.0上在涉及到权限问题时,必须检查权限,请求权限。做个例子说明。分A,B两部分。

A.声明权限,就是我们平常在Manifest中定义的一些权限。在这些权限中,有不同的敏感程度,有些权限是系统必须的这些就好自动授予,有些权限就必须用户手动授予了。例如你开启设备的闪光灯这个权限是自动授予的,但是你读取用户的联系人时系统就会询问用户

是否同意该权限使用。总而言之,当你在Manifest中已经定义好了一些app使用索要用到的权限时,当app运行过程中如果正在使用的功能需要到的权限是不涉及到用户隐私的话,那么这些权限会被系统自动授予,其他情况都会出现系统告知用户。

B.使用过程中检查权限和动态请求权限,用户在使用app的过程中可以对某一权限同意而对某一权限拒绝,这样用户就会充分控制app的功能。更甚至可以在Settings中直接操作该app的某一个权限。例如一个功能要对日历进行写操作,这个操作就需要进行权限检查,

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,

Manifest.permission.WRITE_CALENDAR);

如果返回 PackageManager.PERMISSION_GRANTED这可以直接后续进行写日历操作。

如果返回 PackageManager.PERMISSION_DENIED则需要权限请求了。

在请求权限时,应该出现对话框解释为什么app需要该权限,在解释的时候我们不要期望通过解释来强迫用户授予该权限,权限的说明要简洁明了。

具体如下,请求

if (ContextCompat.checkSelfPermission(thisActivity,

Manifest.permission.READ_CONTACTS)

!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?

if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,

Manifest.permission.READ_CONTACTS)) {

// Show an expanation to the user *asynchronously* -- don't block

// this thread waiting for the user's response! After the user

// sees the explanation, try again to request the permission.

} else {

// No explanation needed, we can request the permission.

ActivityCompat.requestPermissions(thisActivity,

new String[]{Manifest.permission.READ_CONTACTS},

MY_PERMISSIONS_REQUEST_READ_CONTACTS);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an

// app-defined int constant. The callback method gets the

// result of the request.

}

}

请求应答

@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

switch (requestCode) {

case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {

// If request is cancelled, the result arrays are empty.

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the

// contacts-related task you need to do.

} else {

// permission denied, boo! Disable the

// functionality that depends on this permission.

}

return;

}

// other 'case' lines to check for other

// permissions this app might request

} }

如果用户的应答是拒绝,我们应该告诉用户。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: