Android Beginner to Skilled (v)---broadcast

Source: Internet
Author: User

1. Broadcast type: standard broadcast and ordered broadcast . Standard broadcasts are asynchronous broadcasts that are received almost at the same time by all receivers after broadcast, without sequencing, high efficiency, but cannot be truncated. An ordered broadcast is a synchronous broadcast that only one receiver receives this message at the same time, and then continues to pass after execution, and the priority receiver can accept it and truncate the broadcast pass.

Dynamic Registration Case Study: Network change alertBuild Response Class: Class Networkchangereciver extends Broadcastreceiver{            @Override                    public void OnReceive (context context, Intent Intent) {                     Connectivitymanager connectivitymanager= (Connectivitymanager) Getsystemservice (context.connectivity_ SERVICE);                     networkinfo networkinfo=connectivitymanager.getactivenetworkinfo ();                         if ((Networkinfo!=null&&networkinfo.isavailable ()))  {                                &nBsp Toast.maketext (Context, "Network available", Toast.length_short). Show ();                           } else{                                            Toast.maketext (Context, "Network unavailable", Toast.length_short). Show ();                            }
} Register the response when creating the activity, and classify the filter message private Intentfilter intentfilter;//filter message private networkchangereciver networkchangereciver;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinsta                                  Ncestate); Setcontentview (R.layout.activity_main);
                            intentfilter=new Intentfilter ();                              intentfilter.addaction ("Android.net.conn.CONNECTIVITY_CHANGE");                               networkchangereciver=new networkchangereciver ();                                 registerreceiver (Networkchangereciver, Intentfilter);      } destruction listener     @Override          protected void OnDestroy () {             Super.ondestroy ();               unregisterreceiver (Networkchangereciver);       }  finally added permissions to the configuration file <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/>  Static registration Case studies (The benefit is that you can listen to the broadcast without starting the program) Boot upDefines a listener class public class Bootcompletereceiver extends Broadcastreceiver {@Override public void onreceive (Context conte     Xt,intent Intent) {toast.maketext (context, "Start complete", Toast.length_short). Show (); }} Modify Android configuration file <?xml version= "1.0" encoding= "Utf-8"?> < manifest xmlns:android= "http://schemas.android.com /apk/res/android "package=" Com.example.zhb.test2 "> <uses-permission android:name=" Android.permission.ACCESS _network_state "/> <uses-permission android:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/><application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@st Ring/app_name "Android:theme=" @style/apptheme "> <receiver android:name= "Com.example.zhb.Com.BootCompleteReceiver" > <intent-filter> <action android:name= "Android.intent.action.BOOT_COMPLETED"/> </intent-filter> </r Eceiver><activity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <acti On android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUN CHER "/> </intent-filter> </activity> </application> </manifest> 2. Send Standard broadcast and ordered broadcast Standard broadcast : Define a Receive broadcast class public class Mybroadcastreceiver extends Broadcastreceiver {@Override public void onreceive (Context context,inten         T intent) {String Value=intent.getstringextra ("key");     Toast.maketext (Context,value,toast.length_short). Show (); } } Configuration profile Information<receiver android:name= "Com.example.zhb.Com.MyBroadcastReceiver" > <intent-filter> <action android:name= "Com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> </rece Iver> send a message with dataButton Btnbrctestone = (button) Findviewbyid (R.id.btnbrctestone); Btnbrctestone.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View V                 {Intent Intent = new Intent ("Com.example.broadcasttest.MY_BROADCAST"); Intent.putextra ("Key", "I am the Broadcast news!")                 ");             Sendbroadcast (Intent); }         } ordered Messages: Simply change one line of code @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.brocasttest);
Button Btnbrctestone = (button) Findviewbyid (R.id.btnbrctestone); Btnbrctestone.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View V                 {Intent Intent = new Intent ("Com.example.broadcasttest.MY_BROADCAST"); Intent.putextra ("Key", "I am the Broadcast news!")                 "); Sendbroadcast (Intent); Sendorderedbroadcast (intent,null);}         }        ); } Set Priority Receive permissions<receiver android:name= "Com.example.zhb.Com.MyBroadcastReceiver" > <intent-filter android:priority= "> <action android:name= "Com.example.broadcasttest.MY_BROADCAST"/> </intent-filter&         Gt </receiver> truncate broadcast continues to propagate public class Mybroadcastreceiver extends Broadcastreceiver {@Override public void Onrec         Eive (Context context,intent Intent) {String Value=intent.getstringextra ("key"); Toast.maketext (Context,value,toast.length_short). Show (); abortbroadcast ();}} Local broadcast: All previous broadcasts are global broadcasts, that is, broadcasts that are issued can be received by any program, and can also be accepted for broadcast to any program. This can easily lead to security, such as data being monitored by other programs, or other programs that are constantly sending spam broadcasts. Therefore, there is a local broadcasting mechanism. Broadcasts can only be delivered within the application, and receivers can only receive broadcasts from the application. Local broadcasts cannot be registered in a configuration file by means of a static method. public class Brocasttest extends Activity {
Private IntentfilterFilter for intentfilter;//frame private Localreceiverlocalreceiver;//the custom receiver private Localbroadcastmanagerlocalbroadcastmanager;//Framework's local broadcast manager
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.brocasttest);
Localbroadcastmanager=localbroadcastmanager.getinstance (this);//Get instance Button Btnbrctestone = (button) Findviewbyid (R.id.btnbrctestone); Btnbrctestone.setonclicklistener (New View.onclicklistener () {@Override public void onclic K (View v) {//Send local broadcast Intent intent1=new Intent ("Com.example.broadcasttest.LOCAL_BROADCAST"); Localbroadcastmanager.sendbroadcast (intent1);}         }        );
intentfilter=new Intentfilter ();         Intentfilter.addaction ("Com.example.broadcasttest.LOCAL_BROADCAST");         Localreceiver=new Localreceiver (); Localbroadcastmanager.registerreceiver (localreceiver,intentfilter);}
@Override protected void OnDestroy () {Super.ondestroy (); Localbroadcastmanager.unregisterreceiver (localreceiver);}
Class Localreceiver extends Broadcastreceiver{@Override public void onreceive (Context context,intent Intent) {Toast.maketext (cont         Ext, "received local broadcast", Toast.length_short). Show (); }     } }

Android Beginner to Skilled (v)---broadcast

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.