有序广播

本文介绍了一个Android应用中有序广播的实现方式,通过MainActivity发送带有特定ACTION的广播,并由FirstReceiver和SecondReceiver等组件按优先级顺序接收。SecondReceiver中演示了如何使用abortBroadcast()方法中断广播的传递。
摘要由CSDN通过智能技术生成

MianActivity

public class MainActivity extends AppCompatActivity {


    public static final String ACTION = "ordered_broadcast_action";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 发送广播
    public void sendBroadcast(View view) {
        Intent intent = new Intent(ACTION);
        intent.putExtra("msg", "广播内容");

        // 发送有序广播
        sendOrderedBroadcast(intent, null);
    }

}

FirstReceiver(接收器代表)

public class FirstReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        String msg = intent.getStringExtra("msg");
        Log.d("1622", "第一个接收器接到的数据:" + msg);
    }
}

SecondReceiver(注意里面的中断方法)

public class SecondReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        String msg = intent.getStringExtra("msg");
        Log.d("1622", "第二个接收器接到的数据:" + msg);

        // 中断有序广播的传递
        abortBroadcast();//广播顺序播放到这的时候将不再向下播放.
    }
}

清单文件(确定优先级,如果没有优先级按书写顺序发送)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.mobiletrain.android22_orderedbroadcast">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".receiver.FirstReceiver">
            <intent-filter android:priority="1">
                <action android:name="ordered_broadcast_action"/>
            </intent-filter>

        </receiver>

        <receiver android:name=".receiver.SecondReceiver">
            <intent-filter android:priority="2">
                <action android:name="ordered_broadcast_action"/>
            </intent-filter>

        </receiver>

        <receiver android:name=".receiver.ThirdReceiver">
            <intent-filter android:priority="3">
                <action android:name="ordered_broadcast_action"/>
            </intent-filter>

        </receiver>

    </application>

</manifest>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值