Android learning 3 (Intent)

Source: Internet
Author: User

Android learning 3 (Intent)

The previous blog post introduced Activity, which may not be very good at learning. So next we will learn about android Intent, which is the messenger of android and can communicate with each component. I am still doing modification and development on the basis of the above, avoiding too many things. If you haven't read the previous blog post, you can read android learning 2 (Activity) first. Now, let's start.

Use the displayed Intent

1. Based on the previous ActivityTest, we created a layout file named second_layout.xml. The Code is as follows:

 
         
  
 

2. Create an activity named SecondActivity with the code:

package com.wj.test;import android.app.Activity;import android.os.Bundle;import android.view.Window;public class SecondActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.second_layout);}}

3. register the activity in AndroidManifest. xml. The Code is as follows:

     
                          
                                  
               
                                              
 

4. Rewrite the button event in the FirstActivity activity. The modified code is as follows:

Button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub/* Toast. makeText (FirstActivity. this, "you clicked button1", Toast. LENGTH_SHORT ). show (); * // ** Intent usage is divided into display Intent and implicit Intent. below is the display Intent * Intent has multiple constructors, I am using a simple one. The first parameter Context requires a Context for starting * the activity, and the second parameter Class specifies the target activity to be started, use this constructor to construct the Intent * "intent", and then use startActivity (Intent) to start the target activity. * Intent is an important way to interact between components in the android program. It can indicate the action that the current group wants to execute * and transmit data between different components. Intent can be used to start activities, services, and send broadcasts. **/Intent intent = new Intent (FirstActivity. this, SecondActivity. class); startActivity (intent );}});


5. Rewrite the running program and click button1 to jump to SecondActivity.



As shown in the running result, the Intent display is displayed above. It indicates the class to jump. Let's talk about how to use implicit.




Use an implicit Intent

Compared with the displayed Intent, the implicit Intent is much more subtle. It does not specify which activity we want to start, but specifies a series of information such as aciton and category, then the system analyzes the intent and helps us find the appropriate activity to start.

1. Based on the above, we changed it to an implicit Intent. First, we changed the settings in AndroidManifest. xml to configure intent-filter for the registered activity. The configuration content is as follows:

            
                                  
              
         
Note:The android: name can be defined by yourself. However, when creating an Intent, make sure it is consistent with the string here. In the aciton tag, we indicate that the current activity can respond to the action com. wj. test. activitytest. ACTION_START. The tag contains some additional information, which more accurately specifies the category that may be included in the Intent that the current activity can respond. Only sum When the content in matches the action and category specified in the Intent, the activity can respond to the Intent.

2. Modify the Click Event of the button in FirstActivity. The Code is as follows:

Button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub/* Toast. makeText (FirstActivity. this, "you clicked button1", Toast. LENGTH_SHORT ). show (); * // ** Intent usage is divided into display Intent and implicit Intent. below is the display Intent * Intent has multiple constructors, I am using a simple one. The first parameter Context requires a Context for starting * the activity, and the second parameter Class specifies the target activity to be started, use this constructor to construct the Intent * "intent", and then use startActivity (Intent) to start the target activity. * Intent is an important way to interact between components in the android program. It can indicate the action that the current group wants to execute * and transmit data between different components. Intent can be used to start activities, services, and send broadcasts. ** // * Intent intent = new Intent (FirstActivity. this, SecondActivity. class); startActivity (intent); * // use the implicit IntentIntent intent = new Intent ("com. wj. test. activitytest. ACTION_START "); startActivity (intent );}});

We can see that we use another Intent constructor to directly upload the action string, indicating that we want to start the response to com. wj. test. activitytest. ACTION_START: Activity of the action. Is a default category, which is automatically added to the Intent when the startActivity method is called.

Overwrite the running program and it will have the same effect as the displayed Intent.

Note: Only one action can be specified for each Intent, but multiple category can be specified. Next we will add a category.


3. Modify the Click Event of the button in FirstActivity. The Code is as follows:

Button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub/* Toast. makeText (FirstActivity. this, "you clicked button1", Toast. LENGTH_SHORT ). show (); * // ** Intent usage is divided into display Intent and implicit Intent. below is the display Intent * Intent has multiple constructors, I am using a simple one. The first parameter Context requires a Context for starting * the activity, and the second parameter Class specifies the target activity to be started, use this constructor to construct the Intent * "intent", and then use startActivity (Intent) to start the target activity. * Intent is an important way to interact between components in the android program. It can indicate the action that the current group wants to execute * and transmit data between different components. Intent can be used to start activities, services, and send broadcasts. ** // * Intent intent = new Intent (FirstActivity. this, SecondActivity. class); startActivity (intent); * // use the implicit IntentIntent intent = new Intent ("com. wj. test. activitytest. ACTION_START "); intent. addCategory ("com. wj. activitytest. MY_CATEGORY "); startActivity (intent );}});

4. after the modification, you are running the program and you will find that the program crashes. Read the error message and you will find 10-27 01:03:47. 937: E/AndroidRuntime (2824): android. content. activityNotFoundException: No Activity found to handle Intent {act = com. wj. test. activitytest. ACTION_START cat = [com. wj. activitytest. MY_CATEGORY]}, prompting us that we have no activity to respond to our Intent, because we have added intent. addCategory ("com. wj. activitytest. MY_CATEGORY "); While SecondActivity Label does not declare this category, so there is no activity to respond to Intent. We Add the category declaration.

            
                                    
                    
                
           

5. Run again and everything will be normal.


More usage of implicit Intent

Open a browser for a specified page

1. modify the code for clicking the event button in FirstActivity. The main code is as follows:

Button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub/* Toast. makeText (FirstActivity. this, "you clicked button1", Toast. LENGTH_SHORT ). show (); * // ** Intent usage is divided into display Intent and implicit Intent. below is the display Intent * Intent has multiple constructors, I am using a simple one. The first parameter Context requires a Context for starting * the activity, and the second parameter Class specifies the target activity to be started, use this constructor to construct the Intent * "intent", and then use startActivity (Intent) to start the target activity. * Intent is an important way to interact between components in the android program. It can indicate the action that the current group wants to execute * and transmit data between different components. Intent can be used to start activities, services, and send broadcasts. ** // * Intent intent = new Intent (FirstActivity. this, SecondActivity. class); startActivity (intent); * // use the implicit Intent/* Intent intent = new Intent ("com. wj. test. activitytest. ACTION_START "); intent. addCategory ("com. wj. activitytest. MY_CATEGORY "); startActivity (intent); * // more implicit Intent usage // open the browser/** here we specify that the Intent action is Intent. ACTION_VIEW, which is a built-in action of the android system. * its constant is android. intent. action. VIEW, and then use Uri. parse method, returns a URL string Parse the object into a * Uri object and pass the object in by calling the setData () method of Intent. **/Intent intent = new Intent (Intent. ACTION_VIEW); intent. setData (Uri. parse ("http://www.baidu.com"); startActivity (intent );}});

We have specified the Intent data above. For this data, we can also, Configure Label, and more accurately specify the type of data that the current activity can respond.You can configure the following content in the tag:

Android: scheme is used to specify the protocol section of the data, such as the http section in the preceding column.

Android: host is used to specify the host Name of the data, such as www.baidu.com in the upper column.

Android: port is not used to specify the data port, which is usually followed by the Host Name

Android: path is used to specify the host name and the part after the port, such as the content after the domain name in a website

Android: mineType is used to specify the data types that can be processed and can be specified using wildcards.

OnlyWhen the specified content in the tag is exactly the same as the Data carried in the Intent, the current activity will be able to respond to the Intent.


Next, create an activity so that it can respond to the Intent of the web page.

The code for creating a new layout file named third_layout.xml is as follows:

      
          
       
      

Create an Activity ThirdActivity to inherit the Activity. The Code is as follows:

package com.wj.test;import android.app.Activity;import android.os.Bundle;import android.view.Window;public class ThirdActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.third_layout);}}


Register activity

             
                                      
                       
                   
              

In ThirdActivity The action that the current activity can respond to is configured as Intent. ACTION_VIEW constant, while category uses the default value. In addition, android: scheme = "http" in the data tag specifies that the data protocol must be http, in this way, ThirdActivity should be able to respond to an Intent that opens a webpage like a browser.


Run the program and click button1. The result is as follows:



The result of selecting AndroidTest to continue running is as follows:





The following uses Intent to call the call function.

Modify the listening program of button1. The Code is as follows:

Button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub/* Toast. makeText (FirstActivity. this, "you clicked button1", Toast. LENGTH_SHORT ). show (); * // ** Intent usage is divided into display Intent and implicit Intent. below is the display Intent * Intent has multiple constructors, I am using a simple one. The first parameter Context requires a Context for starting * the activity, and the second parameter Class specifies the target activity to be started, use this constructor to construct the Intent * "intent", and then use startActivity (Intent) to start the target activity. * Intent is an important way to interact between components in the android program. It can indicate the action that the current group wants to execute * and transmit data between different components. Intent can be used to start activities, services, and send broadcasts. ** // * Intent intent = new Intent (FirstActivity. this, SecondActivity. class); startActivity (intent); * // use the implicit Intent/* Intent intent = new Intent ("com. wj. test. activitytest. ACTION_START "); intent. addCategory ("com. wj. activitytest. MY_CATEGORY "); startActivity (intent); * // more implicit Intent usage // open the browser/** here we specify that the Intent action is Intent. ACTION_VIEW, which is a built-in action of the android system. * its constant is android. intent. action. VIEW, and then use Uri. parse method, returns a URL string Parse the object into a * Uri object and pass the object in by calling the setData () method of Intent. ** // * Intent intent = new Intent (Intent. ACTION_VIEW); intent. setData (Uri. parse ("http://www.baidu.com"); startActivity (intent); * // realize the call Intent intent = new Intent (Intent. ACTION_DIAL); intent. setData (Uri. parse ("tel: 10086"); startActivity (intent );}});

Run the program. The result is as follows:




Next I will explain how to use Intent to transfer data in activities

Transmit data to the next activity

1. Modify the listening button code of button1

// Transfer data to the next activity/** the Intent provides a series of putExtra () methods for overloading. You can save the data we want to transfer to the Intent *, after another activity is started, you only need to extract the data from the Intent. **/String data = "Hello SecondActivity"; Intent intent = new Intent (FirstActivity. this, SecondActivity. class); intent. putExtra ("extra_data", data); startActivity (intent );

The displayed Intent method is used to start SecondActivity and a string is passed through the putExtra () method. This method receives two parameters. The first parameter is the key, this parameter is used to take values from Intent. The second parameter is the data actually transmitted.


2. Modify SecondActivity to retrieve and print the passed data. The Code is as follows:

package com.wj.test;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.Window;public class SecondActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.second_layout);Intent intent=getIntent();String data =intent.getStringExtra("extra_data");Log.d("SecondActivity", data);}}

Use the getIntent () method to obtain the Intent used to start SecondeActivity, call the getStringExtra () method, and input the corresponding key value to obtain the transmitted data.
Run the program and you can see the following output Hello SecondActivity

Return data to the previous activity:

1. modify the code of the button1 listener:

Button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub/* Toast. makeText (FirstActivity. this, "you clicked button1", Toast. LENGTH_SHORT ). show (); * // ** Intent usage is divided into display Intent and implicit Intent. below is the display Intent * Intent has multiple constructors, I am using a simple one. The first parameter Context requires a Context for starting * the activity, and the second parameter Class specifies the target activity to be started, use this constructor to construct the Intent * "intent", and then use startActivity (Intent) to start the target activity. * Intent is an important way to interact between components in the android program. It can indicate the action that the current group wants to execute * and transmit data between different components. Intent can be used to start activities, services, and send broadcasts. ** // * Intent intent = new Intent (FirstActivity. this, SecondActivity. class); startActivity (intent); * // use the implicit Intent/* Intent intent = new Intent ("com. wj. test. activitytest. ACTION_START "); intent. addCategory ("com. wj. activitytest. MY_CATEGORY "); startActivity (intent); * // more implicit Intent usage // open the browser/** here we specify that the Intent action is Intent. ACTION_VIEW, which is a built-in action of the android system. * its constant is android. intent. action. VIEW, and then use Uri. parse method, returns a URL string Parse the object into a * Uri object and pass the object in by calling the setData () method of Intent. ** // * Intent intent = new Intent (Intent. ACTION_VIEW); intent. setData (Uri. parse ("http://www.baidu.com"); startActivity (intent); * // call/* Intent intent = new Intent (Intent. ACTION_DIAL); intent. setData (Uri. parse ("tel: 10086"); startActivity (intent); * // transfer data to the next activity/** Intent provides a series of reloads of putExtra () methods, you can save the data we want to pass in Intent *. After another activity is started, you only need to extract the data from Intent. ** // * String data = "Hello SecondActivity"; Intent intent = new Intent (FirstActivity. this, SecondActivity. class); intent. putExtra ("extra_data", data); startActivity (intent); * // return data to the previous activity Intent intent = new Intent (FirstActivity. this, SecondActivity. class);/** the startActivityForResult method receives two parameters. One parameter is Intent, and the other parameter is the Request Code *, used to determine the data source in the subsequent callback **/startActivityForResult (intent, 1 );}});


2. Listen to button2

Package com. wj. test; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. view. window; import android. widget. button; public class SecondActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stubsuper. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. second_layout);/* Intent intent = getIntent (); String data = intent. getStringExtra ("extra_data"); Log. d ("SecondActivity", data); * // obtain the Button component Button button2 = (Button) findViewById (R. id. button_2); button2.setOnClickListener (new OnClickListener () {// listener @ Overridepublic void onClick (View v) {// TODO Auto-generated method stubIntent intent = new Intent (); intent. putExtra ("data_return", "Hello FirstActivity"); // The setResult () method receives two parameters. The first parameter is used to return the processing result to the previous activity, generally, // RESULT_ OK or RESULT_CANCELED is used. The second parameter is to pass the Intent with data back, and then call the // finish method to destroy the current active setResult (RESULT_ OK, intent ); finish (); // destroy the current activity }});}}


3. Override the FirstActivity callback Method

// Override the onActivityResult method to obtain the returned result data @ Overrideprotected void onActivityResult (int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubswitch (requestCode) {case 1: if (resultCode = RESULT_ OK) {String returnedData = data. getStringExtra ("data_return"); Log. d ("FirstActivity", returnedData);} break; default: break ;}}


Run the program, click button1, and then click button2. view the log output and you will find the output.

10-28 12:09:09. 396: D/FirstActivity (3755): Hello FirstActivity


Note that the startActivityForResult method is called in an activity to start different activities. The onActivityResult method is called for the data returned by any activity.

If you do not want to click the button2 button to return the result, you can click the back key to return the result. You only need to override the onBackPressed () method of SecondActivity. The Code is as follows:

@ Overridepublic void onBackPressed () {// TODO Auto-generated method stubIntent intent = new Intent (); intent. putExtra ("data_return", "Hello FirstActivity"); // The setResult () method receives two parameters. The first parameter is used to return the processing result to the previous activity, generally, // RESULT_ OK or RESULT_CANCELED is used. The second parameter is to pass the Intent with data back, and then call the // finish method to destroy the current active setResult (RESULT_ OK, intent ); finish (); // destroy the current activity}

Conclusion: The basic usage of Intent is explained above. During data transmission, Intent is the Intent, which is equivalent to the messenger. You can put the data in the Bundle, when you place Bundle in Intent, you can also transmit data. When you are using it, you want to be able to refer to the opposite. You can view the api and source code without any other methods. Intent will explain it here, the next article describes the lifecycle of an activity.


Reprinted Please note: http://blog.csdn.net/j903829182/article/details/40502495




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.