Chapter 5 of my Android system: interaction between activities and activities through Intent, androidintent

Source: Internet
Author: User

Chapter 5 of my Android system: interaction between activities and activities through Intent, androidintent
Intent action in the activity:

Itent is an important way to directly exchange various components in the Android program. You can specify the current component to execute the task and directly exchange data with each component.
At the same time, Intent can often start activities, start services, and send broadcasts.

Category

1. Display Intent and implicit Intent

Show Intent operation 1. First create an Android Project

 

We need to create an activity in the rec directory-layout resource to explain the explicit and implicit Operations respectively.

Right-click to create a new activity_second.xml layout file.

Add a button component under the file.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:id="@+id/button2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Button2" /></LinearLayout>

 

2. Create an activity

After adding the button component, we also give the button a name named button2 and a unique id, and then create an Activity SecondActivity under the src directory project package to inherit the Activity class and make it an Activity class.

Then rewrite the onCreate () method and set the context layout file for the activity.

Package com. example. intentdome; import android. app. activity; import android. OS. bundle; public class SecondActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_second); // read the layout file we just created in the layout resource file }}

3. register an activity in the AndroidManifest. xml project configuration file.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.intentdome"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="17"        android:targetSdkVersion="17" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <activity android:name=".SecondActivity"            >        </activity>    </application></manifest>

 

The above steps have been completed, so let's start the next step.

Bind event to button

1. Bind a click event to the MainActivit View File

@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the Button object Button btn1 = (Button) findViewById (R. id. button1); // bind a listener event btn1.setOnClickListener (new OnClickListener () {@ Override // trigger this operation when you click the mouse) {}});}

 

2. Create intent object

The Intent constructor has multiple constructor Intent (Context packageCntext, Class <?> Cls) first parameter: Specify the context to be started second parameter: Specify the target activity to be started

// Obtain an intent object
Intent intent = new Intent (MainActivity. this, SecondActivity. class );

 

 

3. Between activitiesInteraction

@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the Button object Button btn1 = (Button) findViewById (R. id. button1); // bind a listener event btn1.setOnClickListener (new OnClickListener () {@ Override // trigger this operation when you click the mouse) {// get an Intent object // implement the direct interaction between the activity and the activity intent Intent = new Intent (MainActivity. this, SecondActivity. class); // call startActivity (intent );}});}

Implicit Intent operation

Features: Hiding it does not explicitly indicate that we want to start that activity, but abstract and specify a series of actions, category, and other information.

1. Implement implicit operations: Open the AndroidManifest. xml file and rewrite the activity content.

    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <activity android:name=".SecondActivity">            <intent-filter >                <action android:name="com.example.intentdome.ACTION_START"/>                 <category android:name="android.intent.category.DEFAULT"/>            </intent-filter>        </activity>    </application>

 

2. Rewrite the MainActivity. java button and click the event.

@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the Button object Button btn1 = (Button) findViewById (R. id. button1); // bind a listener event btn1.setOnClickListener (new OnClickListener () {@ Override // trigger this operation when you click the mouse) {/* // get an Intent object // implement the direct interaction between the activity and the activity intent Intent = new Intent (MainActivity. this, SecondActivity. class); // call startActivity (intent); */Intent intent = new Intent ("com. example. intentdome. ACTION_START "); startActivity (intent );}});}

 

3. Run: output the same result

Start internal activities of other programs with implicit instructions

In fact, implicit display can not only start the activity of your own program, but also start the activity of other programs, so that multiple Android applications can be shared, so that the program can directly exchange data with the program, in this way, we do not need to write other program activities to operate.

The next case shows how to use your own program to call the browser of the system to open a blog webpage.

1. Rewrite the MainActivity. java button and click the event.

@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the Button object Button btn1 = (Button) findViewById (R. id. button1); // bind a listener event btn1.setOnClickListener (new OnClickListener () {@ Override // trigger this operation when you click the mouse) {Intent intent = new Intent (Intent. ACTION_VIEW); intent. setData (Uri. parse ("http://www.cnblogs.com/xiaotaojing/"); startActivity (intent );}});}

In the above example, Intent starts an activity operation through Intent. In fact, Intent can directly exchange and transmit data between the activity and the activity. Let's take a look at what the process is like.

Intent implements data transmission settings for activity data

Intetn provides a putExtra () method for data storage in the form of key-value pairs, equivalent to the setattivity () method of the scope object of the Serlet, puExtra () methods provide method overloading to store transmitted data in Intent.

When starting an activity to another activity, you only need to retrieve data from the Intent.

@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the Button object Button btn1 = (Button) findViewById (R. id. button1); // bind a listener event btn1.setOnClickListener (new OnClickListener () {@ Override // trigger this operation when you click the mouse) {Intent intent = new Intent (MainActivity. this, SecondActivity. class); intent. putExtra ("data", "Hello SecondActivity"); startActivity (intent );}});}
Get Data

You can use the getStringExtra () method to obtain the stored data.

Intent. getStringExtra (set the parameter name)

 

Then write the following code in ScondActivity. java:

Package com. example. intentdome; import android. app. activity; import android. OS. bundle; import android. widget. toast; public class SecondActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_second); // display the data Toast in the prompt box. makeText (this, getIntent (). getStringExtra ("data"), Toast. LENGTH_SHORT ). show ();}}

Run the test

Carrying data to return to the previous activity

Since a single activity can transmit data to the next activity, can the returned data be the previous activity? Actually, yes. When you click the return key, isn't it possible to return to the previous activity? Haha, but the returned results do not contain data.

What can I do to return a previous activity after a duplicate activity? Data can also be carried. In fact, we need to use startActivityForResulte (), which has two parameters.

The first parameter is the Intent object and the second parameter is the request result code.

Btn1.setOnClickListener (new OnClickListener () {@ Override // trigger this operation when you click the mouse. public void onClick (View v) {Intent intent = new Intent (MainActivity. this, SecondActivity. class); startActivityForResult (intent, 1 );}});

Second, write the following code in SecondActivity. java:

@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_second); Button btn2 = (Button) findViewById (R. id. button2); btn2.setOnClickListener (new OnClickListener () {@ Override public void onClick (View arg0) {Intent intent = new Intent (); // set the intent value to be returned. putExtra ("data_return", "I have returned the previous activity"); // set the returned result setResult (RESULT_ OK, intent); finish (); // execute before destruction }});

We have set the starActivityForReturn () method to start SecondActivity. After SecondActivity is destroyed, an onActivityResult () method of the activity will be called. Therefore, I need to rewrite it in MainActivity. java.

OnActivityResult () method

 @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {    super.onActivityResult(requestCode, resultCode, data);        switch (requestCode) {     case 1: if(resultCode==RESULT_OK){Toast.makeText(this, data.getStringExtra("data_return"),Toast.LENGTH_SHORT).show() ; } break;      default:break;}    }

3. Test

Executed successfully

Is it true that this lecture has a powerful knowledge point? Haha, this has achieved the effect of redirecting between pages on a website and carrying data at the same time.

 

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.