android自定义权限,Android 自定义权限详解
一、自定义权限与使用
在用户app中,自定义权限往往设定在 四大组件上Activity,Service,BroadcastReceiver,ContentProvider,作为app的一部分,如果不允许组件被其他调用,设置权限也是一种保护方式。
在这里我们以BroadcastReceiver为例,假定其属于appA:
package test.common.home;
public class StickyBroadcastReceiver extends BroadcastReceiver
{
public static final String Action = “com.sample.test.sticky.broadcast.receiver”;
public static final String PERMISSION = “com.sample.test.permission.sticky.receiver”;
@Override
public void onReceive(Context context, Intent intent)
{
int checkCallingOrSelfPermission = context.checkCallingOrSelfPermission(PERMISSION);
//权限的检测(实际上,这种检测系统会自动检测,如果通过的话才会调用onReceive方法,我们这里特意指出,就是为了明白系统检测方式是怎样的)
//如果要检测出2种效果,只能使用该BroadcastReceiver自身应用来实现,因为自身应用没权限也可访问该广播
if(PackageManager.PERMISSION_GRANTED == checkCallingOrSelfPermission)
{
Toast.makeText(context, “授权成功”, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, “授权失败”, Toast.LENGTH_SHORT).show();
}
if(intent!=null&&Action.equals(intent.getAction()))
{
Toast.makeText(context, intent.getStringExtra(“info”), Toast.LENGTH_SHORT).show();
}
}
}
在到Manifest.xml文件中注册
首先自已权限并使用自定义权限
然后注册广播
android:exported=”true”
android:permission=”com.sample.test.permission.sticky.receiver” >
属性说明
android:exported=”true” —->是否外部允许访问,低版本中默认是true,高版本默认是false,请注意
android:permission=”com.sample.test.permission.sticky.receiver” —->外部访问是需要检测的权限
然后我们创建appB,在appB中创建一个Activity用来发送广播:
Intent intent = new Intent(StickyBroadcastReceiver.Action);
intent.putExtra(“info”, “hello world”);
sendBroadcast(intent);
二、自定义权限测试
测试一:将appA中的StickyBroadcastReceiver设置为android:exported设置为false,不设置权限android:permission
测试结果,发送广播失败:
Permission Denial: Accessing service ComponentInfo
java.lang.SecurityException: Not allowed to bind to service Intent
测试二:将appA中的StickyBroadcastReceiver设置为android:exported=true,不设置权限android:permission
测试结果:
广播接收正常
测试三:将appA中的StickyBroadcastReceiver设置为android:exported设置为true,设置权限android:permission=”com.sample.test.permission.sticky.receiver”
在appB中不设置
测试结果
Permission Denial
测试四:在测试三的基础上在AppB设置
测试结果:广播接收正常
由上可知,权限运行正常,所以你可以试试了。
附加:
android:protectionLevel —->保护级别,看这里http://www.xuebuyuan.com/1873075.html
try doing it!
还没有评论,来说两句吧...