Android uses two ways of registering receiver

Source: Internet
Author: User

1.

Package Com.example.myreceiver;import Android.os.bundle;import Android.app.activity;import android.content.Intent; Import Android.content.intentfilter;import Android.view.menu;import Android.view.view;public class MainActivity Extends Activity {private Mybroadcastreceiver receiver = new Mybroadcastreceiver ();p rivate intentfilter filter = new Inten Tfilter ("Com.feng.intent"); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} public void Start (view view) {Intent Intent = new Intent ("Com.feng.intent"); Intent.putextra ("Name", "Wang"); Sendbroadcast (intent);} @Overrideprotected void OnPause () {super.onpause (); Unregisterreceiver (receiver);} @Overrideprotected void Onresume () {super.onresume (); Registerreceiver (receiver, filter);}}

Package Com.example.myreceiver;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.util.log;public class Mybroadcastreceiver extends broadcastreceiver{@ overridepublic void OnReceive (Context arg0, Intent arg1) {System.out.println ("Good!i ' ve recevied u!"); LOG.E ("Mybroadcastreceiver", "Good!i ' ve recevied u!");}}
The advantage of this approach is that it is flexible to use and highly controllable.

Another is to register in the Mainfest.xml. The benefit is that as long as the application is installed, it will remain in the listening state.

      <receiver android:name= "Com.example.myreceiver.MyBroadcastReceiver" >            <intent-filter >                < Action android:name= "com.feng.intent"/>            </intent-filter>        </receiver>



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.