首页 > 代码库 > 04_ Broadcast Receiver

04_ Broadcast Receiver

  Broadcast是广播,和Android内的事件一样,它可以发出一个广播(事件),注册了该广播接收器(事件监听器)的所有组件都会接收到该广播,从而调用自己的响应方法(事件响应处理)。

 

  下面将详细的阐述如何发送Broadcast和使用BroadcastReceiver过滤接收的过程:

 

  首先在需要发送信息的地方,把要发送的信息和用于过滤的信(ActionCategory)装入一个Intent对象,然后通过调用 sendOrderBroadcast()sendStickyBroadcast()方法,把 Intent对象以广播方式发送出去。

 

  当Intent发送以后,所有已经注册的BroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent相匹配,若匹配则就会调用BroadcastReceiveronReceive()方法。所以当我们定义一个BroadcastReceiver的时候,都需要实现onReceive()方法。

 

  代码如下:

 

package com.example.broadcastdemo;import android.app.Activity;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {    private Button btnSendBroadCast, btnRegBCR, btnUnregBCR;    private final MyBC mybc = new MyBC();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btnSendBroadCast = (Button) findViewById(R.id.btnSendBroadCast);        btnRegBCR = (Button) findViewById(R.id.btnRegBCR);        btnUnregBCR = (Button) findViewById(R.id.btnUnregBCR);        btnSendBroadCast.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // Intent i = new Intent(MainActivity.this, MyBC.class);                Intent i = new Intent(MyBC.ACTION);                i.putExtra("txt", "Hello, LJY!");                sendBroadcast(i);            }        });        //Register a BroadCast Receiver        btnRegBCR.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // an IntentFilter is an address.                registerReceiver(mybc, new IntentFilter(MyBC.ACTION));            }        });        btnUnregBCR.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                unregisterReceiver(mybc);            }        });    }}
View Code

 

package com.example.broadcastdemo;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class MyBC extends BroadcastReceiver {    public static final String ACTION = "com.example.broadcastdemo.intent.action.MyBC";        @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        System.out.println("onReceive data =  "http://www.mamicode.com/+ intent.getStringExtra("txt"));            }}
View Code

 

04_ Broadcast Receiver