Android: dynamically register BroadcastReceiver

Source: Internet
Author: User

Android: dynamically register BroadcastReceiver

Annotations are directly written in the code, which is intuitive. I think these definition system broadcast macros are not very good;

MainActivity. java:

Package com. vrinux. broadcastdemo; import android. app. activity; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. OS. bundle; import android. util. log; import android. widget. toast; public class MainActivity extends Activity {// defines a filter; private IntentFilter intentFilter; // defines a broadcast listener; private NetChangRecei Ver netChangReceiver; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. fragment_main); // instantiate the filter; intentFilter = new IntentFilter (); // Add the filtered Action value; intentFilter. addAction (Intent. ACTION_AIRPLANE_MODE_CHANGED); // instantiate the broadcast listener; netchanger ER = new netChangReceiver (); // register the broadcast listener with the filter; registerReceiver (NetChangReceiver, intentFi) Lter) ;}@ Override protected void onDestroy () {// TODO Auto-generated method stub super. onDestroy (); // cancel the registration of the broadcast listener when the Activity is destroyed; unregisterReceiver (netChangReceiver);} // create a broadcast listener that inherits the BroadcastReceiver; class NetChangReceiver extends BroadcastReceiver {// rewrite the onReceive method. The entity of this method is the Execution Code after receiving the broadcast. @ Override public void onReceive (Context context, Intent intent) {// TODO Auto-generated method stub Log. I ("MainA Ctivity "," starting flight mode ~ "); Toast. makeText (MainActivity. this," flight mode Start ~ ", Toast. LENGTH_SHORT). show ();}}}

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.