Broadcastreceiver is used to listen to the system global broadcast message, because Broadcastreceiver is a global listener, so it can be very convenient to implement communication between the different components of the system
It takes two steps to start it.
1. Create a broadcastreceiver intent that needs to be started
2. Invoke the Sendbroadcast or Sendorederedbroadcast method of the context to start the specified broadcastreceiver
The key is to setaction ("xxx") when creating intent, and broadcastreceiver to create its filter, or specify it in the code, or specify it in the XML
Here is a simple example of a program that sends messages to a broadcast
Sender-Side Main interface code
[Java]View Plaincopyprint?
- Package WangLi.Service.Broadcast;
- Import android.app.Activity;
- Import android.content.Intent;
- Import Android.os.Bundle;
- Import Android.view.View;
- Import Android.view.View.OnClickListener;
- Import Android.widget.Button;
- Public class broadcast extends Activity {
- Button send;
- @Override
- public void OnCreate (Bundle savedinstancestate) {
- super.oncreate (savedinstancestate);
- Setcontentview (R.layout.main);
- //Get buttons in the interface
- Send = (Button) Findviewbyid (r.id.send);
- Send.setonclicklistener (new Onclicklistener () {
- @Override
- public void OnClick (View arg0) {
- //Create Intent Object
- Intent Intent = new Intent ();
- //Set the Action property of Intent
- Intent.setaction ("wangli.test");
- Intent.putextra ("msg", "simple Message");
- //Send broadcast
- Sendbroadcast (Intent);
- }
- });
- }
- }
Then create a Broadcastreceiver listener
[Java]View Plaincopyprint?
- Package WangLi.Service.Broadcast;
- Import Android.content.BroadcastReceiver;
- Import Android.content.Context;
- Import android.content.Intent;
- Import Android.widget.Toast;
- Public class Myreceiver extends Broadcastreceiver {
- @Override
- public void OnReceive (context context, Intent Intent) {
- Toast.maketext (
- Context
- "The action received by intent is:" + intent.getaction () + "\ nthe message content is:"
- + Intent.getstringextra ("msg"), . Show ();
- }
- }
The receiver is configured to Androidmanifest.xml, primarily intent filter
[HTML]View Plaincopyprint?
- <receiver android:name= "myreceiver" >
- < intent-filter>
- < Action android:name= "wangli.test" />
- </intent-filter>
- </receiver< span class= "tag" >>
Note that Broadcastreceiver has an expiration time of 10 seconds, and if a time-consuming operation should be done in the service, Broadcastreceiver is only suitable for short-term computing tasks, because its life cycle is very short
Beginner Android,broadcastreceiver send and receive broadcasts