首页 > 技术文章 > 有序广播与无序广播

doitbyyourself 2017-01-06 17:25 原文

有序广播:按照优先级一级一级的进行传递,类似红头文件下发,有序广播可以被终止,数据可以被修改

sendOrderedBroadcast

无序广播:类似新闻联播,无论你看不看,其都正常播报,无序广播不能被终止,数据不能被修改

sendBroadcast(intent);

 

假设在APK-A中实现一个按钮,点击该按钮就会发送一个无序的广播,但是有没有APK接收到该广播,对于发送无序广播的APK并不关心,如果APK-B配置了接收APK-A发送的广播过滤事件,则APK-B可以接收到该广播

APK-A中实现代码:

 public void click(View view)
    {
        Intent intent = new Intent();
        intent.putExtra("name", "发送无序广播的内容");
        intent.setAction("myself.broadcastreceiver");
        sendBroadcast(intent);
    }

APK-B中实现代码:

1、实现一个类继承BroadcastReceiver并且复写onReceive方法

public class ReceiverMyselfBroadCast extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String name = intent.getStringExtra("name");
        Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
    }
}

2、在AndroidManifest.xml中配置事件过滤器

 <receiver android:name=".ReceiverMyself">
            <intent-filter>
                <action android:name="myself.broadcastreceiver"/>
            </intent-filter>
 </receiver>

 

推荐阅读