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);

你可能感兴趣的:(基础,android)