BroadcastReceiver 小结

BroadcastReceiver is like a doctor in hospital, it works only when patient comes. Doctors are classfied according to their study area. Similarily, BroadcastReceiver has different actions limitation. To use BroadcastReceiver, we need to register it. There are two methods to register a BroadcastReceiver:

1. Dynamically register a BroadcastReceiver using registerReceiver(); For example:

//MainActivity.java
public class MainActivity extends Activity {
  private Button sendButton;
  private TestReceiver smsReceiver=null;
  private static final String SMS_ACTION="android.provider.Telephony.SMS_RECEIVED";
  @Override
  public void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      sendButton=(Button)findViewById(R.id.sendButton);
      sendButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            System.out.println("clicked");
//create a new object of BroadcastReceiver class smsReceiver
=new TestReceiver();
//create an IntentFilter object and specify its action IntentFilter intent
=new IntentFilter(); intent.addAction(SMS_ACTION);
//registerReceiver by calling registerReceiver using Activity class, the object receiver is TestReceiver object with intentfilter MainActivity.
this.registerReceiver(smsReceiver,intent); } }); } }
//TestReceiver.java
public
class TestReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub // After receiving a message, we print out 'onReceive' System.out.println("onReceive"); } }

2. Besides above method, we can also statically prepare the broadcastReceiver. For example:

the above TestReceiver can also be registered using AndroidManifest.xml.

<receiver android:name=".TestReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

Overall, the complete code for the above example is put here: 

posted @ 2014-06-03 09:48  丸子No1  阅读(185)  评论(0编辑  收藏  举报