BroadcastReceiver就是一个广播消息接收者。
广播之间信息的传递是通过Intent对象来传递的。
- Intent调用分为显示调用和隐式调用两种,由于这里能通知到所有的接收者,所以肯定不能利用显示调用,只有利用隐式调用Intent对象了
- 显式intent是指明确指出此intent是启动哪个activity.
隐式intent是指并没有指出要启动哪个activity,而要系统自动去判断并启动匹配的activity.
首先构造一个接收器:
广播的传递是靠Intent的,OnReceive的第二个参数,就是广播传过来的Intent。
- public class MyReceiver extends BroadcastReceiver {
- private static final String TAG = "MyReceiver";
- @Override
- public void onReceive(Context context, Intent intent) {
- // TODO Auto-generated method stub
- String msg = intent.getStringExtra("msg");
- Log.i(TAG, "MyReceiver:"+msg);
- }
- }
大家可能会想,就这么着,就能收到广播了?当然不是,上面我们说了,通过隐式Intent来发送广播的,我们肯定要匹配这个Intent啊,匹配Intent的术语是Activity中的,在广播这里,叫要注册,也就是要注册一下,什么样的Intent能接收。
android:name:对应接收器的类名;我们自定义的类名叫MyReceiver ,所以这里写".MyReceiver
"
代码如下:(MainActivity.java)
真正的发送代码在send()函数中,在这个函数中可以看到,我们通过传进去刚才注册的MyRecevier的action,来构造一个隐式Intent,然后利用PutExtra放进去一个额外信息(这个不是必须的,我们仅仅是为了跟踪这个消息传到了哪里去,在《详解Intnent》系统文章中有讲怎样构造一个隐式Intent),与StartActivity不同的是,这里利用的是sendBroadcast(intent)来发送这个Intent;
MyReceiver的广播接收 注册代码如下:(静态注册)
- <receiver android:name=".MyReceiver">
- <intent-filter>
- <action android:name="android.intent.action.MY_BROADCAST"/>
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- </receiver>
intent-filter标签里,同样是必须的两项:action和category;我在这里自定义了action的名字,等下隐式发送通过时,就是利用匹配action来接收通知的。
这里特别注意<activity> 标签与<receiver>标签的构造。完全相同!!!!!!!
完全相同体现在:
- 1、所处位置:都直属<application>标签;
- 2、参数构造基本一样;都有android:name,都有<intent-filter>;
- 3、都是通过Intent传递参数,也都是通过Intent进行匹配!!!!
最后是发送广播:
我们在主页面加一个Button,当点击Button时发送广播消息。
布局文件如下:(activity_main.xml)
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context="com.example.test_brocast_blog.MainActivity" >
- <Button
- android:id="@+id/sent_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="发送Broadcast" />
- </RelativeLayout>
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button btn= (Button)findViewById(R.id.sent_btn);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- send();
- }
- });
- }
- public void send() {
- Intent intent = new Intent("android.intent.action.MY_BROADCAST");
- intent.putExtra("msg", "hello receiver.");
- sendBroadcast(intent);
- }
- }