android 6.0更新了全新的权限机制,在使用一些涉及用户隐私的权限时,会让用户做出选择是否该app可以使用此权限。
本文章是根据鸿翔大神的Android 6.0运行时权限处理完全解析博客思路开始学习的。
在查看本文章之前,希望大家可以移步官方开发文档 使用权限。在该文章中,详细描述了新版本的权限机制的更改,声明权限未发生改变,需要详细观看在运行时请求权限,查看权限最佳做法可以避免糟糕的用户体验。
在权限中,分为Normal Permissions和Dangerous Permissions两种类别。其中Normal Permissions属于正常权限,不需要用户授权的;而Dangerous Permissions属于危险权限,与用户隐私密切相关,所以授权给用户。我们在程序中就需要对这种危险权限提供用户授权处理,保证app的正常运行。官方文档给出了正常权限和危险权限,不清楚的可以在官网查看。
#####申请权限的小案例 1).在AndroidManifest中添加权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
复制代码
2).Activity中的具体申请方法(参考官网的课程步骤)
package com.example.mypremission;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final int MY_PERMISSIONS_EXTERNAL_STORAGE_REQ_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
}
public void requestPermission(){
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//检查到未授权该权限信息
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//上一次用户拒绝了开启此权限!
// 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(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_EXTERNAL_STORAGE_REQ_CODE);
// 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_EXTERNAL_STORAGE_REQ_CODE: {
// 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.
Toast.makeText(this, "申请成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "申请失败", Toast.LENGTH_SHORT).show();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
复制代码
运行程序:
接下来我会研究权限机制的封装,完成权限批量申请的好办法!