Android Tour-intent and Broadcastreceiver (modified the online article a lot of shortcomings, focus on the reference to ANDROID4 advanced programming)

Source: Internet
Author: User

First, intent function and classification

Intent is a messaging mechanism that can be used within programs and between programs, primarily by using the class name to explicitly start a service or Activity② to perform an action intent on ① basis, and to handle the ③ broadcast a certain time has occurred.

Ii. using intent to initiate activity

1. Explicitly start an activity

The so-called explicit start, that is, explicitly specifying the class name we want to start activity on, such as when we want to open intentactivity when the button in Mainactivity is pressed, we can use the following code:

<span style= "White-space:pre" ></span>if (v==btn1) {Intent intent=new Intent (); Intent.setclass ( Mainactivity.this, Intentactivity.class); startactivity (intent);}
Note that all activity is stored in an activity stack, and when we call StartActivity, Intentactivity will go through creat start resume and eventually run, And the intentactivity will move to the top of the acticity stack. But when we press back (or the code executes finish ()), the activity is removed from the top of the activity stack.

2. Implicit activation activity

An implicit start activity is to anonymously start an appropriate program component in response to an action request. If we want to implicitly start an activity that opens a contact:

Implicitly select contacts, note that using startactivity does not start the interface Intent Intent=new Intent (intent.action_pick,uri.parse ("content://contacts/ People ")); Startactivityforresult (intent,pick_contact_subactivity);
3. Start activity and capture the results returned by the child activity

As we can see above, the simple use of startactivity mainactivity does not get the result of intentactivity processing. At this point we need to Startactivityforresult:

But just using this interface is not enough, we need an interface to listen to the structure, we need to overload mainactivity in protected void onactivityresult (int requestcode, int resultcode , Intent data):

In the mainactivity:

<pre name= "code" class= "java" ><pre name= "code" class= "Java" >//define intent identification code private static final int show_ Subactivity=1;<pre name= "code" class= "java" >intent intent=new Intent (); Intent.setclass (Mainactivity.this, Intentactivity.class);//The Incoming identification code uniquely identifies show_subactivity, launches intent to obtain the results returned by the next page Startactivityforresult (intent, Show_ subactivity);

@Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub    Super.onactivityresult (Requestcode, ResultCode, data);    if (requestcode==show_subactivity)    {    switch (resultcode) {case    result_canceled:    {    Bundle bd= Data.getextras ();    Edittxt.settext (bd.getstring ("text"));    break;    }    Case RESULT_OK:    {    Bundle bd=data.getextras ();    Edittxt.settext (bd.getstring ("text"));    break;    }    Default: Break;}}}    

in the intentactivity:

Switch (V.getid ()) {case r.id.resultcancel:{intent intent=new Intent (); Intent.setclass (Intentactivity.this, Mainactivity.class); Intent.putextra ("Text", "cancel:i am from Intentactivity!and pass to me on childactivity finished!" ); Setresult (result_canceled,intent); finish (); break;} Case R.id.resultok:{intent intent=new Intent (); Intent.setclass (Intentactivity.this, Mainactivity.class); Intent.putextra ("text", "Ok:am from Intentactivity!and pass back me on childactivity finished!"); Setresult (result_ok,intent); Finish (); break;} Default:break;}
Parse: We are in Startactivityforresult (intent, show_subactivity);show_subactivity, in fact, is an integer greater than 0, used to identify the corresponding intent; In order to accept result, the Onactivityresult (int requestcode, int resultcode, Intent data), note that Requestcode is the Intent identifier, that is, the Show_sunactivity,resultcode in the above is the intentactivity Setresult (result_ok,intent); The result value returned- result_ok,date is setresult (result_ok,intent); passed back to the intent.

Iii. use of Intent broadcast events

1, the most basic broadcast event send and accept:

Broadcast send, very simple, generate a intent, set the action, broadcast directly:

<span style= "White-space:pre" ></span>intent intent=new Intent (broad_ui_string); Intent.putExtra ("Str", "Update UI by Broadcast!"); Sendbroadcast (Intent);

Broadcast registration is best to register the broadcast before the broadcast is sent:

<span style= "White-space:pre" ></span>//Register broadcast Receiver     registerreceiver (new Mybroadcastreceiver, New Intentfilter (broad_ui_string));

Note: The broad_ui_string in the above is a custom unique string, because the broadcast can not only be used to exchange data within the application, but also for inter-system application Exchange data, it is generally named by the traditional package name prefix method.

Before registering, we need to implement our own receiver, inherit Broadcastreceiver, we will broadcast the intent bound data again processing

public class Mybroadcastreceiver extends Broadcastreceiver {        @Override public        void OnReceive (context context, Intent Intent) {           //todo:react to the Intent received.        String actionstring=intent.getaction ();        if (Actionstring.equals (broad_ui_string))        {        //change the value in the next activity        STRING Str=intent.getstringextra ("str ");            Intent newintent=new Intent ();            Newintent.setclass (mainactivity.this,intentactivity.class);            Newintent.putextra ("str", str);            Context.startactivity (newintent);        }        else if (actionstring.equals (local_action))        {        edittxt.settext (Intent.getstringextra ("str"));        }        }     }
Logoff of broadcasts: when we are no longer broadcasting, usually the interface hangs or stops, the receiver needs to be unregistered:

@Overrideprotected void OnPause () {unregisterreceiver (receiver); Super.onpause ();}
Note that the handler in the receiver needs to be completed within 5 seconds, otherwise the Force close dialog will be displayed. Many times, we want to be able to respond to some broadcasts when our application is closed, to add a receiver tag to the application node in manifest, to specify the receiver class name and filter identifier:

<receiver android:name= ". Mybroadcastreceiver "  <intent-filter>    <action android:name=" packagename.classname.BROAD_UI_ STRING "/>  </intent-filter></receiver>
This way, even if our application is turned off, it responds to the broadcast.

2. Orderly Broadcasting

3, broadcast sticky Intent, in some tutorials still appear, but after Android 5.0 will gradually obsolete, it is no longer discussed.

4. Localbroadcastmanager (local broadcast manager)

As the name implies, its use for local data-driven message is a lightweight handler, more efficient broadcast model.

The procedure is similar to the General broadcast manager, except that you get Localbroadcastmanager first:

Lbm=localbroadcastmanager.getinstance (Mainactivity.this);
Send the Sendbroadcast to Lbm.sendbroadcast, the registration will be registerreceiver to Lbm.registerreceiver, log off when Unregisterreceiver changed to Lbm.unregisterrec Eiver

The following is an example of all the code, the project file I will also put in the end:

Package Com.example.intentandbroadcast;import Android. R.string;import Android.app.activity;import Android.content.broadcastreceiver;import Android.content.Context; Import Android.content.intent;import android.content.intentfilter;import android.net.uri;import android.os.Bundle; Import Android.support.v4.content.localbroadcastmanager;import Android.view.*;import Android.view.view.onclicklistener;import android.widget.*; @SuppressWarnings ("Unused") public class Mainactivity Extends Activity {Button btn1; Button Btn2,btn3,btn4,btn_broad_ui,btn_local_broad; EditText Edittxt; TextView TV; Localbroadcastmanager LBM; Mybroadcastreceiver receiver; Define intent identification code private static final int show_subactivity=1; private static final int pick_contact_subactivity=2;  public static final String broad_ui_string= "Com.example.intentbraodcast.BROAD_UI";  public static final String local_action= "Com.example.intentbraodcast.LOCAL_ACTION";     void Getviewdefinition () {btn1= (Button) Findviewbyid (R.ID.BTN1); Btn2=(Button) Findviewbyid (R.ID.BTN2);     btn3= (Button) Findviewbyid (R.ID.BTN3);     btn4= (Button) Findviewbyid (R.ID.BTN4);     Btn_broad_ui= (Button) Findviewbyid (R.ID.BTN_BROAD_UI);     edittxt= (EditText) Findviewbyid (R.id.edittext);     tv= (TextView) Findviewbyid (R.id.textview);     Btn_local_broad= (Button) Findviewbyid (R.ID.BTN_LOCAL_BROAD_UI);    Lbm=localbroadcastmanager.getinstance (Mainactivity.this); Receiver=new Mybroadcastreceiver (); } public class OnButtonClick implements Onclicklistener {@Overridepublic void OnClick (View v) {//TODO auto-generated Meth OD stubif (v==btn1) {Intent intent=new Intent (); Intent.setclass (Mainactivity.this, intentactivity.class);// The incoming identification code uniquely identifies show_subactivity, launches intent, to get the results returned by the next page Startactivityforresult (intent, show_subactivity);} else if (V==BTN3) {//Trigger external intent Call Intent Intent=new Intent (Intent.action_dial,uri.parse ("tel:13237170570")); StartActivity (intent);} else if (V==BTN4) {//Implicitly select contacts, note that using startactivity does not start the interface Intent Intent=new Intent (Intent.action_pick,uri.parse ("Content://contacts/people ")); Startactivityforresult (intent,pick_contact_subactivity);} else if (v==btn_broad_ui) {Intent intent=new Intent (broad_ui_string); Intent.putextra ("str", "Update UI by Broadcast!"); Sendbroadcast (intent);} else if (v==btn_local_broad) {//Set local broadcast, more efficient: Intent intent=new Intent (local_action); Intent.putextra ("str", "I am created by local broadcast! ");  Lbm.sendbroadcast (intent);}}       } @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Getviewdefinition ();        OnButtonClick btnclick=new OnButtonClick ();        Btn1.setonclicklistener (Btnclick);        Btn3.setonclicklistener (Btnclick);        Btn4.setonclicklistener (Btnclick);        Btn_broad_ui.setonclicklistener (Btnclick);    Btn_local_broad.setonclicklistener (Btnclick); } @Overrideprotected void Onresume () {//TODO auto-generated method Stubsuper.onresume ();//Register Broadcast Receiver Registe Rreceiver (ReceivEr, new Intentfilter (broad_ui_string)); Register LOCAL Broadcastlbm.registerreceiver (receiver, new Intentfilter (local_action)); } @Overrideprotected void OnPause () {unregisterreceiver (receiver); Lbm.unregisterreceiver (receiver); Super.onpause ()        ;}     @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub    Super.onactivityresult (Requestcode, ResultCode, data); if (requestcode==show_subactivity) {switch (ResultCode) {case result_canceled: {Bundle Bd=data.getextras (    );    Edittxt.settext (bd.getstring ("text"));    Break    } case RESULT_OK: {Bundle bd=data.getextras ();    Edittxt.settext (bd.getstring ("text"));    Break    } Default:break; }}} @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; this adds items        To the action Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; } @OverRide public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); } public class Mybroadcastreceiver extends Broadcastreceiver {@Override public void OnReceive (Context Co        ntext, Intent Intent) {//todo:react to the Intent received.        String actionstring=intent.getaction (); if (Actionstring.equals (broad_ui_string)) {//change the value in the next activity STRING Str=intent.getstringextra ("str"            );            Intent newintent=new Intent ();            Newintent.setclass (Mainactivity.this,intentactivity.class);            Newintent.putextra ("str", str);  Context.startactivity (newintent);      } else if (Actionstring.equals (local_action)) {Edittxt.settext (Intent.getstringextra ("str")); }        }     }}

Package Com.example.intentandbroadcast;import Java.security.publickey;import Com.example.intentandbroadcast.mainactivity.mybroadcastreceiver;import Android.app.activity;import Android.app.pendingintent.canceledexception;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.os.bundle;import Android.support.v4.content.localbroadcastmanager;import Android.view.*;import Android.view.view.onclicklistener;import android.widget.*;p ublic class Intentactivity extends Activity {Button Cancel , ok,btn_local; TextView txtintenttextview;intentfilter Filter;        String stickystring;void getdefinition () {cancel= (Button) Findviewbyid (r.id.resultcancel);        ok= (Button) Findviewbyid (R.id.resultok);        Btn_local= (Button) Findviewbyid (r.id.btn_localintent); txtintenttextview= (TextView) Findviewbyid (r.id.textintent); }public class Onbtnclick implements onclicklistener{@Overridepublic void OnClick (View v) {//TODO auto-generated Method Stubswitch (V.getid ()) {case r.id.resultcancel:{intent intent=new Intent (); Intent.setclass (Intentactivity.this, Mainactivity.class); Intent.putextra ("Text", "cancel:i am from Intentactivity!and pass back me on Childactivity finished! "); Setresult (result_canceled,intent); finish (); break;} Case R.id.resultok:{intent intent=new Intent (); Intent.setclass (Intentactivity.this, Mainactivity.class); Intent.putextra ("text", "Ok:am from Intentactivity!and pass back me on childactivity finished!"); Setresult (result_ok,intent); Finish (); break;}    Default:break;}}}        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Mined area, this start of the XML hit the wrong tune for a long time Setcontentview (r.layout.activity_intent);        Getdefinition ();//Test Startactivyforresult Cancel.setonclicklistener (New Onbtnclick ());    Ok.setonclicklistener (New Onbtnclick ()); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//InflaTe the menu;        This adds items to the action bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }    }
Eclipse Engineering Address: http://download.csdn.net/detail/tianyuan521521/8604875









Android Tour-intent and Broadcastreceiver (modified the online article a lot of shortcomings, focus on the reference to ANDROID4 advanced programming)

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.