Android Four components: the use of broadcastreceiver

Source: Internet
Author: User

Broadcastreceiver

Role:

Listen App to and respond to broadcast messages sent by the app

Application Scenarios:

    • AndroidCommunication between different components (including: Between in-app/different applications)
    • Multi-threaded communication
    • Communication with the Android system under certain circumstances

such as: Phone call, when the network is available, headset plug in

Initial use of Broadcastreceiver: implements sending messages to Broadcastrecever, Broadcastreceiver received messages on console output

Step One:

Activity_main.xml layout:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    xmlns:app=" Http://schemas.android.com/apk/res-auto "    xmlns:tools=" http://schemas.android.com/ Tools "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical"    tools:context= "Com.contentprovide.liuliu.brodcast_demo1. Mainactivity "><button    android:id=" @+id/btn "    android:layout_width=" Wrap_content "    android: layout_height= "Wrap_content"    android:text= "send Message"    /></linearlayout>

Step Two:

Create a broadcastreceiver(custom class inherits Broadcastreceiver, overriding the OnReceive method ),

Package Com.contentprovide.liuliu.brodcast_demo1;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;public class Myreceiver extends Broadcastreceiver {    @ Override public    void OnReceive (context context, Intent Intent) {        String s = Intent.getstringextra ("date");        System.out.println ("=================== received the message is:" +s);    }}

This step will automatically register the system in the Androidmanifest.xml file Broadcastreceiver

Step three: Java code passes information to the broadcast receiver

Package Com.contentprovide.liuliu.brodcast_demo1;import Android.content.intent;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;import Android.widget.button;public class Mainactivity extends Appcompatactivity {    Button btn;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        BTN = (Button) Findviewbyid (R.ID.BTN);        Btn.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (view view) {                Intent Intent = new Intent (mainactivity.this, myreceiver.class);                Intent.putextra ("date", "11111");//                Transmit message                sendbroadcast (intent);}}        );}    }

implementation results:

Dynamic registration and logoff Broadcastreceiver


When you create a broadcastreceiver in Android studio, the system will automatically register statically, but many times, in order to optimize the program, dynamically register when needed, do not need to log off in time

Step One: Activity_main.xml layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= " Http://schemas.android.com/apk/res/android "xmlns:app=" Http://schemas.android.com/apk/res-auto "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Androi d:orientation= "vertical" tools:context= "Com.contentprovide.liuliu.brodcast_demo2. Mainactivity "> <button android:id=" @+id/btn_send "android:layout_width=" Wrap_content "Androi d:layout_height= "wrap_content" android:text= "send Message"/> <button android:id= "@+id/btn_reg" Android Oid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "register receiver"/> <Butto n android:id= "@+id/btn_unreg" android:layout_width= "wrap_content" android:layout_height= "wrap_content "Android:text=" logoff receiver "/></LINEARLAYOUT> 

Step two: Create a broadcastrecever that declares an object as the type of the broadcast sink

Myreceiver.java

Package Com.contentprovide.liuliu.brodcast_demo2;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;public class Myreceiver extends Broadcastreceiver {// Declares a string variable that stores the path of the current broadcast sink as the type of the receiving broadcast public     static final String path = "Com.contentprovide.liuliu.brodcast_demo2" ;    @Override public    void OnReceive (context context, Intent Intent) {        String s = Intent.getstringextra ("date");        System.out.println ("=================== received the message is:" +s);    }}

Step three: Dynamic registration and logoff of broadcast receivers using Java code

Package Com.contentprovide.liuliu.brodcast_demo2;import Android.content.intent;import Android.content.intentfilter;import Android.support.v7.app.appcompatactivity;import Android.os.Bundle;import Android.view.view;import Android.widget.button;public class Mainactivity extends Appcompatactivity implements    View.onclicklistener {Button btn_send, Btn_reg, Btn_unreg;    Intent Intent;    Myreceiver myreceiver = null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Btn_send = (Button) Findviewbyid (r.id.btn_send);        Btn_reg = (Button) Findviewbyid (R.id.btn_reg);        Btn_unreg = (Button) Findviewbyid (R.id.btn_unreg);        Btn_send.setonclicklistener (this);        Btn_reg.setonclicklistener (this);        Btn_unreg.setonclicklistener (this);    Intent = new Intent (Myreceiver.path); } @Override public void OnClick (view view) {switch (View.getid ()){Case R.id.btn_send:intent.putextra ("date", "11111");                Sendbroadcast (Intent);            Break Case R.ID.BTN_REG://adds a judgment statement to prevent duplicate registrations and repeated logoff if (myreceiver = = null) {Myreceiver = new Myre Ceiver ();//sets the type of the received broadcast, invokes the string variable declared in Myreceiver.java in parentheses following the instantiation Intentfilter intentfilt ER = new Intentfilter (myreceiver.path);//Registered Broadcast receiver Registerreceiver (Myreceiver, Inten                Tfilter);            } break; Case R.id.btn_unreg:if (Myreceiver! = null) {//Logoff broadcast sink Unregisterre                    Ceiver (Myreceiver);                Myreceiver = null;        } break; }    }}

Effect: Click the transfer message before clicking Register Player, the console has no message output. Click Register Player and then click Send Message, console has message output. Click Logout Player and then click Send Message, console also no message output

    • Multiple system broadcasts are built into Android: the corresponding broadcasts are issued as long as the basic operation of the phone is involved (such as power-on, network status changes, taking photos, etc.)
    • Each broadcast has a specific intent-filter (including a specific action), and the Android system broadcasts the action as follows:
System Operation Action
Monitor network changes Android.net.conn.CONNECTIVITY_CHANGE
Turn off or turn on airplane mode Intent.action_airplane_mode_changed
Charge or power change Intent.action_battery_changed
Low battery power Intent.action_battery_low
The battery is fully charged (that is, it emits a broadcast when it changes from low to full Intent.action_battery_okay
After system boot is complete (broadcast only once) intent.action_boot_completed
When you press the camera button (the hardware key) Intent.action_camera_button
Screen lock Screen Intent.action_close_system_dialogs
When the device's current settings are changed (interface language, device orientation, etc.) Intent.action_configuration_changed
Plug in the ear machine Intent.action_headset_plug
The SD card was not removed correctly but was removed (correct removal method: Set--SD card and device memory--Uninstall SD card) Intent.action_media_bad_removal
Inserting an external storage device (e.g. SD card) Intent.action_media_checking
Install APK successfully intent.action_package_added
Successfully deleted APK Intent.action_package_removed
Restarting the device Intent.action_reboot
Screen is turned off Intent.action_screen_off
Screen is open intent.action_screen_on
When the system is shut down Intent.action_shutdown
Restarting the device Intent.action_reboot

Note: When using the system broadcast, only need to define the relevant action when registering the broadcast receiver, do not need to send the broadcast manually, when the system has related actions will automatically broadcast the system

Recommended Blog: HTTPS://WWW.JIANSHU.COM/P/CA3D87A4CDF3

Android Four components: the use of broadcastreceiver

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.