Android之广播机制—自定义广播

来源:互联网 发布:淘宝活动时间 编辑:程序博客网 时间:2024/05/01 21:53
自定义广播:
即在Manifest文件中注册的接收器action标签中写上自己定义的接收器标签。
一般是<action android:name="包名.后面大写加下划线组合"/>
发送广播的action标签和其一致就可以了。

示例代码:

<!--这是注册在Manifest中的自定义广播接收器。--> <receiver android:name=".OtherBroadcast">            <intent-filter>                <action android:name="com.example.tangyi.receiver3.MY_BROADCAST"/>            </intent-filter>        </receiver>

这是接收器类:

public class OtherBroadcast extends BroadcastReceiver {    @Override    public void onReceive(Context context,Intent intent){        Toast.makeText(context,"这是广播接收器",Toast.LENGTH_SHORT).show();    }}

这是发送广播的监听器:

Button button=(Button)findViewById(R.id.button);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent=new Intent("com.example.tangyi.receiver3.MY_BROADCAST");                sendOrderedBroadcast(intent,null);            }        });
可以看到,这个自定义广播接收器,为了能让他接收到自定义的广播,
我们做了一个发送自定义广播的按钮。利用显式intent将action的值传入自定义的标签。
这样这个自定义的广播接收器同样能接收到我们所发送到的广播。

0 0