Android基础总结四:BroadcastReceiver总结二(广播权限设置)

为广播设置权限要考虑两方面的问题:

1. 限制接收者—–作为广播的发送者,希望限制广播的接收者,只让特定的应用组件接收到发出的广播;

2. 限制发送者——作为广播的接收者,希望限制广播的发送者,只接收具有权限的发送者发送的广播。

限制接收者

发送方要发送广播,希望只拥有相应权限的BroadcastReciver接收到:

1.首先发送方需要定义一个权限

在发送方的AndroidManifest.xml中,声明一个权限,名为com.anddle.receiver.receivebroadcast

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <permission
        android:name="com.anddle.receiver.receivebroadcast"
        android:label="receiver permission"
        android:protectionLevel="normal" />

    <application>
        ……
    </application>
</manifest>

2.接收方需要声明上面定义的权限

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <!--声明要使用的权限-->
    <users-permission android:name = "com.anddle.receiver.receivebroadcast"/>
    <application
        ......>
        <!--假设采用的是静态定义的接收机-->
        <receiver
           android:name=".MyReceiver"
           android:enabled="true"
           android:exported="true">
           <intent-filter>
               <action android:name="custom.action.mybroadcast"/>
               <category android:name="android.intent.category.DEFAULT" />
           </intent-filter>
        </receiver>
    </application>

</manifest>

3.发送方发送广播

Intent intent = new Intent("custom.action.mybroadcast");
//第二个参数是广播权限的名称
sendBroadcast(intent ,"com.anddle.receiver.receivebroadcast");

限制发送者

接收方设置权限,只接收特定发送者发来的广播:

1.首先接收方需要定义一个权限

在接收方的AndroidManifest.xml中,声明一个权限,名为com.anddle.receiver.sendbroadcast

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <permission
        android:name="com.anddle.receiver.sendbroadcast"
        android:label="receiver permission"
        android:protectionLevel="normal" />

    <application>
        ……
    </application>
</manifest>

2.给接收方的BroadcastReceiver添加权限

AndroidManifest.xml中,对BroadcastReceiver设置android:permission属性为com.anddle.receiver.sendbroadcast

<receiver
    android:name=".MyReceiver"
    android:enabled="true"
    android:exported="true"
   android:permission="com.anddle.receiver.sendbroadcast" />

3.给发送方设置权限

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.anddle.calculator">

    <uses-permission android:name="com.anddle.receiver.sendbroadcast"/>

    <application
            ....../>

</manifest>

4.发送方发送广告

Intent i = new Intent("custom.action.mybroadcast");
sendBroadcast(i);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值