Android 6.0 运行时权限处理完全解析(转)
Normal Permissions如下
Dangerous Permissions:
2.检查权限
!= PackageManager.PERMISSION_GRANTED) {
}else{
//
}
这里涉及到一个API,ContextCompat.checkSelfPermission,主要用于检测某个权限是否已经被授予,方法返回值为PackageManager.PERMISSION_DENIED或者PackageManager.PERMISSION_GRANTED。当返回DENIED就需要进行申请授权了。
3.申请授权
4.处理权限申请回调
@Override
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;
}
}
}
ok,对于权限的申请结果,首先验证requestCode定位到你的申请,然后验证grantResults对应于申请的结果,这里的数组对应于申请时的第二个权限字符串数组。如果你同时申请两个权限,那么grantResults的length就为2,分别记录你两个权限的申请结果。如果申请成功,就可以做你的事情了~
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.
}
那么将上述几个步骤结合到一起就是:
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.
}
}
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void testCall(View view)
{
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
} else
{
callPhone();
}
}
public void callPhone()
{
Intent intent = new Intent(Intent.ACTION_CALL);
Uri data = Uri.parse("tel:" + "10086");
intent.setData(data);
startActivity(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
callPhone();
} else
{
// Permission Denied
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
在Android 6.x上运行是,点击testCall,即会弹出授权窗口,如何你Allow则直接拨打电话,如果Denied则Toast弹出”Permission Denied”。
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
} else
{
callPhone();
}
public static void needPermission(Fragment fragment, int requestCode, String[] permissions)
requestPermissions(fragment, requestCode, permissions);
}
@TargetApi(value = Build.VERSION_CODES.M)
private static void requestPermissions(Object object, int requestCode, String[] permissions)
{
if (!Utils.isOverMarshmallow())
{
doExecuteSuccess(object, requestCode);
return;
}
List<String> deniedPermissions = Utils.findDeniedPermissions(getActivity(object), permissions);
if (deniedPermissions.size() > 0)
{
if (object instanceof Activity)
{
((Activity) object).requestPermissions(deniedPermissions.toArray(new String[deniedPermissions.size()]), requestCode);
} else if (object instanceof Fragment)
{
((Fragment) object).requestPermissions(deniedPermissions.toArray(new String[deniedPermissions.size()]), requestCode);
} else
{
throw new IllegalArgumentException(object.getClass().getName() + " is not supported");
}
} else
{
doExecuteSuccess(object, requestCode);
}
}
Utils.findDeniedPermissions其实就是check没有授权的权限。
#Utils
public static List<String> findDeniedPermissions(Activity activity, String... permission)
{
List<String> denyPermissions = new ArrayList<>();
for (String value : permission)
{
if (activity.checkSelfPermission(value) != PackageManager.PERMISSION_GRANTED)
{
denyPermissions.add(value);
}
}
return denyPermissions;
}
那么上述的逻辑就很清晰了,需要的3种参数传入,先去除已经申请的权限,然后开始申请权限。 ok,我相信上面代码,大家扫一眼就可以了解了。 (2)处理权限回调 对于回调,因为要根据是否授权去执行不同的事情,所以很多框架也需要些一连串的代码,或者和前面的申请代码耦合。不过这个框架还是比较方便的,也是我选择它来讲解的原因。
回调主要做的事情:
1.了解是否授权成功。
2.根据授权情况进行回调。
对于第一条逻辑都一样;对于第二条,因为涉及到两个分支,每个分支执行不同的方法。 对于第二条,很多框架选择将两个分支的方法在申请权限的时候进行注册,然后在回调中根据requestCode进行匹配执行,不过这样需要在针对每次申请进行对象管理。 不过这个框架采取了一种很有意思的做法,它利用注解去确定需要执行的方法,存在两个注解:
@PermissionFail(requestCode = 100)
利用反射根据授权情况+requestCode即可找到注解标注的方法,然后直接执行即可。 大致的代码为:
@Override
PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}
private static void requestResult(Object obj, int requestCode, String[] permissions,int[] grantResults)
{
List<String> deniedPermissions = new ArrayList<>();
for (int i = 0; i < grantResults.length; i++)
{
if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
{
deniedPermissions.add(permissions[i]);
}
}
if (deniedPermissions.size() > 0)
{
doExecuteFail(obj, requestCode);
} else
{
doExecuteSuccess(obj, requestCode);
}
}
首先根据grantResults进行判断成功还是失败,对于成功则:
private static void doExecuteSuccess(Object activity, int requestCode)
Method executeMethod = Utils.findMethodWithRequestCode(activity.getClass(),
PermissionSuccess.class, requestCode);
executeMethod(activity, executeMethod);
}
#Utils
public static <A extends Annotation> Method findMethodWithRequestCode(Class clazz, Class<A> annotation, int requestCode)
{
for (Method method : clazz.getDeclaredMethods())
{
if (method.isAnnotationPresent(annotation))
{
if (isEqualRequestCodeFromAnntation(method, annotation, requestCode))
{
return method;
}
}
}
return null;
}
根据注解和requestCode找到方法,然后反射执行即可。失败的逻辑类似,不贴代码了。
ok,到此我们的运行时权限相对于早起版本的变化、特点、以及如何处理和封装都介绍完了。
不过对于上面讲解的库,肯定有人会说:运行时反射会影响效率,没错,不过我已经在上述代码的基础上将运行时注解改成Annotation Processor的方式了,即编译时注解,这样的话,就不存在反射损失效率的问题了。本来准备fork修改,然后PR,结果写完,改动太大,估计PR是不可能通过了,所以另起项目了,也方便后面的做一些扩展和维护。 详见库:https://github.com/hongyangAndroid/MPermissions.
六、MPermissions用法
对外的接口和PermissionGen基本一致,因为申请只需要三个参数,抛弃了使用原本类库的单例的方式,直接一个几个静态方法,简单整洁暴力。 贴一个用法:
{
private Button mBtnSdcard;
private static final int REQUECT_CODE_SDCARD = 2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnSdcard = (Button) findViewById(R.id.id_btn_sdcard);
mBtnSdcard.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
MPermissions.requestPermissions(MainActivity.this, REQUECT_CODE_SDCARD, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@PermissionGrant(REQUECT_CODE_SDCARD)
public void requestSdcardSuccess()
{
Toast.makeText(this, "GRANT ACCESS SDCARD!", Toast.LENGTH_SHORT).show();
}
@PermissionDenied(REQUECT_CODE_SDCARD)
public void requestSdcardFailed()
{
Toast.makeText(this, "DENY ACCESS SDCARD!", Toast.LENGTH_SHORT).show();
}
}
转自:http://blog.csdn.net/lmj623565791/article/details/50709663;