Android tour-Intent and BroadcastReceiver)

Source: Internet
Author: User

Android tour-Intent and BroadcastReceiver)

I. Functions and categories of Intent

Intent is a message transmission mechanism that can be used within and between programs. Its main usage is as follows: ① use a class name to explicitly start a service or Activity ② execute the intent of an action on the basis of ① and perform related processing ③ broadcast has occurred at a certain time.

Ii. Start Activity with Intent

1. Start an Activity explicitly

Explicit start means explicitly specifying the Class Name of the Activity to be started. For example, to open IntentActivity when the Button in Mainactivity is pressed, you can use the following code:

 

if(v==btn1){Intent intent=new Intent();intent.setClass(MainActivity.this, IntentActivity.class);startActivity(intent);}
Note: All activities are stored in an Activity stack. After startActivity is called, IntentActivity will run after Creat start resume, and IntentActivity will be moved to the top of the Acticity stack. However, when we press back (or execute finish () in the Code), the Activity will be deleted from the top of the Activity stack.

 

2. Start the Activity implicitly.

To start an Activity implicitly, start an appropriate program component anonymously to respond to the action request. For example, we want to implicitly start the Activity that opens the contact:

 

// Select contacts implicitly. Note that the Intent intent = new Intent (Intent. ACTION_PICK, Uri. parse (content: // contacts/people); startActivityForResult (intent, PICK_CONTACT_SUBACTIVITY );
3. Start the Activity and capture the results returned by the Child Activity.

 

As we can see above, using startActivity MainActivity alone cannot get the result after IntentActivity is processed. In this case, startActivityForResult is required:

However, this interface is not enough. We need an interface to listen to the structure. In this case, we need to reload protected void onActivityResult (int requestCode, int resultCode, Intent data) in MainActivity ):

In MainActivity:

 

 
 
// Define the intent identifier private static final int SHOW_SUBACTIVITY = 1;
Intent intent = new Intent (); intent. setClass (MainActivity. this, IntentActivity. class); // pass in the unique identifier SHOW_SUBACTIVITY, start intent, in order to get the result startActivityForResult (intent, SHOW_SUBACTIVITY) returned on the next page );

 @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 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 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;}
Resolution: In startActivityForResult (intent, SHOW_SUBACTIVITY), when SHOW_SUBACTIVITY is passed in, it is actually an integer greater than 0 to identify the corresponding Intent. To accept the Result, onActivityResult (int requestCode, int resultCode, Intent data). Note that requestCode is the identifier of Intent, that is, SHOW_SUNACTIVITY in the preceding section, and resultCode is setResult (RESULT_ OK, intent) in IntentActivity ); returned Result value-RESULT_ OK, date is setResult (RESULT_ OK, intent); returned intent.

 

3. Use Intent to broadcast events

1. Send and accept the most basic broadcast events:

Sending a broadcast is very simple. It generates an Intent, sets the Action, and broadcasts the broadcast directly:

 

public static final String BROAD_UI_STRING=com.example.intentbraodcast.BROAD_UI; 
Intent intent=new Intent(BROAD_UI_STRING);intent.putExtra(str, update ui by broadcast!);sendBroadcast(intent);

 

You are advised to register a broadcast before sending the broadcast:

 

// Register the Broadcast Receiver er registerReceiver (new MyBroadcastReceiver, new IntentFilter (BROAD_UI_STRING ));

 

Note: The BROAD_UI_STRING in the preceding section is a unique custom string. Because broadcast can be used not only for internal data exchange within an application, but also for data exchange between systems, therefore, the traditional package name prefix is generally used for naming.

Before registering, we need to implement our own receiver and inherit BroadcastReceiver. We can process the data bound to the broadcasted Intent again.

 

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 of String str = intent in the next activity. 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 ));}}}
Broadcast cancellation: When we stop broadcasting, the receiver is usually logged out when the interface is suspended or stopped:

 

 

 @Overrideprotected void onPause() { unregisterReceiver(receiver);super.onPause();}
It should be noted that the processing program in the receiver needs to be completed within five seconds, otherwise the Force CLose dialog box will be displayed. Many times, we want our application to respond to some broadcasts when it is closed. We need to add a receiver tag to the application node in Manifest to specify the receiver class name and filter identifier:

 

 

       
 
In this way, our application can respond to the broadcast even if it is disabled.

 

2. Ordered Broadcast

3. Broadcast Sticky Intent, which still appears in some tutorials, but will be discarded gradually after android 5.0, so we will not discuss it any more.

4. LocalBroadcastManager)

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

The operation procedure is similar to that of the normal broadcast manager, except that the LocalBroadcastManager must be obtained first:

 

lbm=LocalBroadcastManager.getInstance(MainActivity.this);
Change sendBroadcast to lbm. sendBroadcast when sending the message, change registerReceiver to lbm. registerReceiver when registering the message, and change unregisterReceiver to lbm. unregisterReceiver when canceling the message.

 

The following is all the code for the example, and I will put the project file to 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; impor T android. widget. *; @ SuppressWarnings (unused) public class MainActivity extends Activity {Button btn1; Button btn2, btn3, btn4, btn_broad_ui, scheme; EditText edittxt; TextView TV; LocalBroadcastManager lbm; extends er; // define the intent identifier 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); extends ER = new MyBroadcastReceiver ();} public class OnButtonClick implements OnClickListener {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubif (v = btn1) {Intent intent = new Intent (); intent. setClass (MainActivity. this, I NtentActivity. class); // pass in the unique identifier SHOW_SUBACTIVITY to start intent to obtain the result returned on 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 a contact, note that startActivity does not enable Intent intent = new Intent (Intent. ACTION_PICK, Uri. parse (content: // contacts/people); startActivityForRes Ult (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 (); listener (btnclick); btn4.setOnClickListener (btnclick); listener (btnclick ); btn_local_broad.setOnClickListener (btnclick) ;}@ Overrideprotected void onResume () {// TODO Auto-generated method stubsuper. onResume (); // register Broadcast Receiver er registerReceiver (receiver er, 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 will // 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 context, Intent intent) {// TODO: React to the Intent already ed. string actionString = intent. getAction (); if (actionString. equals (BROAD_UI_STRING) {// change the value of String str = intent in the next activity. 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. sup Port. v4.content. localBroadcastManager; import android. view. *; import android. view. view. onClickListener; import android. widget. *; public 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) findView ById (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); // minefield, this started xml has been wrong 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 will // 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 );}}

 



 

 



 

 

Related Article

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.