Broadcast receiver components in ANDROID development applications _android

Source: Internet
Author: User

Broadcastreceiver (broadcast receiver) is one of the four major components of Android. The following is a detailed description of the use of the broadcast receiver component.

The following is an overview of Broadcastreceiver in Android Doc:

The ① broadcast receiver is a component that focuses on receiving broadcast notification information and making corresponding processing. Many broadcasts originate from system code-for example, notifying time zone changes, low battery power, taking a picture, or changing the language option for the user. Applications can also broadcast--for example, notifying other applications that some data downloads are complete and available.

The ② application can have any number of broadcast sinks to respond to all of the notification information that it is interested in. All sinks inherit from the Broadcastreceiver base class.

The ③ broadcast receiver does not have a user interface. However, they can initiate an activity to respond to the information they receive, or use Notificationmanager to notify the user. Notifications can be used in a number of ways to attract users ' attention-flashing back lights, shaking, playing sound, and so on. In general, a persistent icon is placed on the status bar, and the user can open it and get the message.

There are two kinds of broadcast events in Android , one is System broadcast events, such as: action_boot_completed (triggered after system startup), action_time_changed (triggered when system time changes), ACTION _battery_low (triggered when low power) and so on. The other is our custom broadcast event.

The process of broadcasting events

① Registered Broadcast event: There are two ways to register, one is static registration, is defined in the Androidmanifest.xml file, the registered broadcast receiver must inherit Broadcastreceiver, the other is dynamic registration, is registered in the program using CONTEXT.REGISTERRECEIVER, registered broadcast receiver equivalent to an anonymous class. Both ways require intentfilter.

② sends broadcast events: sent by Context.sendbroadcast, intent to pass the action used when registering.

③ Receive broadcast event: When a broadcast is heard by the receiver, its onreceive () method is invoked and the intent object containing the message is passed to it. Do not exceed 5s of code execution time in OnReceive, or Android will eject timeout dialog.

Below I demonstrate the use of custom broadcast events and system broadcast events through code.

STEP1: Registers the broadcast event in the Mainactivity OnStart method. The static registration method is in the Androidmanifest.xml file.

STEP2: Clicking the corresponding button will trigger the appropriate way to send the broadcast message.

/** * mainactivity * @author zuolongsnail * */public class Mainactivity extends activity {private Button SE 
  NDSTATICBTN; 
  Private Button senddynamicbtn; 
  Private Button sendsystembtn; 
  private static final String staticaction = "com.byread.static"; 
  private static final String dynamicaction = "Com.byread.dynamic"; 
  USB Device Connection private static final String systemaction = intent.action_power_connected; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    SENDSTATICBTN = (Button) Findviewbyid (r.id.send_static); 
    SENDDYNAMICBTN = (Button) Findviewbyid (r.id.send_dynamic); 
    SENDSYSTEMBTN = (Button) Findviewbyid (R.id.send_system); 
    Sendstaticbtn.setonclicklistener (New Myonclicklistener ()); 
    Senddynamicbtn.setonclicklistener (New Myonclicklistener ()); 
  Sendsystembtn.setonclicklistener (New Myonclicklistener ()); Class Myonclicklistener implements ONCLicklistener{@Override public void OnClick (View v) {//Send custom static registered broadcast message if (V.getid () = = R.id.send_st 
        atic) {log.e ("mainactivity", "Send custom static registration broadcast message"); 
        Intent Intent = new Intent (); 
        Intent.setaction (staticaction); Intent.putextra ("MSG", "Receive static registered broadcast success!") 
        "); 
      Sendbroadcast (Intent);  
        //Send custom dynamic register broadcast message else if (v.getid () = = r.id.send_dynamic) {log.e ("mainactivity", "Send custom dynamic registration broadcast message"); 
        Intent Intent = new Intent (); 
        Intent.setaction (dynamicaction); Intent.putextra ("MSG", "Receive dynamic registration Broadcast success!") 
        "); 
      Sendbroadcast (Intent); //Send system dynamic register broadcast message. 
      When the phone is connected to the charging device, the system sends its own broadcast message. 
        else if (v.getid () = = R.id.send_system) {log.e ("mainactivity", "Send system dynamic Registration broadcast message"); 
        Intent Intent = new Intent (); 
        Intent.setaction (systemaction); Intent.putextra ("msg", "is charging ....") 
      "); 
    }} @Override protected void OnStart () {Super.onstart (); Log.E ("Mainactivity", "Registered broadcast event"); 
    Registers a custom dynamic broadcast message Intentfilter filter_dynamic = new Intentfilter (); 
    Filter_dynamic.addaction (dynamicaction); 
    Registerreceiver (Dynamicreceiver, filter_dynamic); 
    Registration system dynamic Broadcast message Intentfilter Filter_system = new Intentfilter (); 
    Filter_system.addaction (systemaction); 
  Registerreceiver (Systemreceiver, Filter_system); Private Broadcastreceiver Dynamicreceiver = new Broadcastreceiver () {@Override public void onreceive (Context, Intent Intent) 
      {LOG.E ("mainactivity", "Receive custom dynamic registration Broadcast message"); 
        if (Intent.getaction (). Equals (Dynamicaction)) {String msg = Intent.getstringextra ("msg"); 
      Toast.maketext (Context, MSG, toast.length_short). Show (); 
  } 
    } 
  }; Private Broadcastreceiver Systemreceiver = new Broadcastreceiver () {@Override public void onreceive (conte 
      XT context, Intent Intent) {log.e ("mainactivity", "Receive system dynamic register broadcast message"); if (intent.getactIon (). Equals (Systemaction)) {String msg = Intent.getstringextra ("msg"); 
      Toast.maketext (Context, MSG, toast.length_short). Show (); 
} 
    } 
  }; 
 }

STEP3: Receive broadcast messages. The following are two statically registered broadcast receivers.

/** 
 * Custom static registered broadcast message receiver 
 * @author zuolongsnail * * */Public 
class Staticreceiver extends Broadcastreceiver { 
 
  @Override public 
  void OnReceive (context context, Intent Intent) { 
    String msg = Intent.getstringextra ("msg"); 
    Toast.maketext (Context, MSG, toast.length_short). Show (); 
   
/** 
 * System static registered broadcast message receiver 
 * * 
 @author zuolongsnail * */Public 
class Systemreceiver extends Broadcastreceiver { 
 
  @Override public 
  void OnReceive (context context, Intent Intent) { 
    if ( Intent.getaction (). Equals (Intent.action_battery_low)) { 
      log.e ("Systemreceiver", "low battery hint"); 
      Toast.maketext (Context, "Your mobile phone is low, please charge", Toast.length_short). Show ();}} 
 

Here is the Androidmanifest.xml file:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.byread "android:versioncode=" 1 "android:versionname=" 1.0 "> <application android:icon=" @ Drawable/icon "android:label=" @string/app_name "> <activity android:name=". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action android:name=" Android. Intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-f Ilter> </activity> <!--registers a custom static broadcast receiver--> <receiver android:name= ". Staticreceiver "> <intent-filter> <action android:name=" com.byread.static "/> </in Tent-filter> </receiver> <!--registration system static broadcast receiver--> <receiver android:name= ". Systemreceiver "> <intent-filter> <action android:name=" Android.intent.action.BATTERY_LOW "/> </intent-filter> </receiver> </application> </manifest> 
 

Interface Layout File Main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:orientation=" vertical "android:layout_width=" fill_parent " 
  android:layout_height=" Fill_parent "> 
  <textview android:layout_width=" fill_parent "android:layout_height=" Wrap_content " 
    android:text= "@string/hello"/> <button android:id= "@+id/send_static" android:layout_width= 
  Content " 
    android:layout_height=" wrap_content "android:text=" sends custom static registered broadcasts "/> 
  <button android:id=" @+ Id/send_dynamic "android:layout_width=" wrap_content " 
    android:layout_height=" wrap_content "android:text=" Send custom dynamic enrollment broadcast "/> 
  <button android:id=" @+id/send_system "android:layout_width=" 
    Android : layout_height= "wrap_content" android:text= "Send system dynamic Register broadcast"/> 
</LinearLayout> 

The explanation is over, but I don't know for myself that the system broadcasts events if I sendbroadcast in the program, it's a custom broadcast. If not, is it the system itself that sends the corresponding action broadcast? Please tell me about the students who know, and then thank them first.

Run the interface:


The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.