Android Getting Started Intent Shuttling Between Activity

  • 2021-12-21 04:56:17
  • OfStack

Directory overview 1. Explicit Intent2. Implicit Intent uses Intent to pass data 1. Pass data to the next Activity 2. Return data to the last Activity

Overview

Intent is an important way of interaction among components in Android program. It can not only indicate the action that the current component wants to perform, but also transfer data between different components

Intent can be roughly divided into two types: explicit Intent and implicit Intent

1. Explicit Intent

Intent has multiple overloads of constructors, one of which is Intent(Context packetContext, Class<?> cls) This constructor takes two parameters:

The first parameter Context requires a context to start Activity The second parameter, Class, specifies the target Activity that you want to start

From this constructor, you can build Intent, which is provided in the Activity class startActivity() Method to start Activity specifically, which receives 1 Intent parameter. We define a button button1 to modify the click event


button1.setOnClickListener {
    val intent = Intent(this, SecondActivity::class.java)
    startActivityForResult(intent)
}

When Activity is started in this way, the intention of Intent is 10 points obvious, so it is called explicit Intent

2. Implicit Intent

Implicit Intent does not specify which Activity you want to start, but specifies a series of more abstract information such as action and category, and then leaves it to the system to analyze this Intent and help us find a suitable Activity to start

Through the < activity > Label configuration < intent-filter > You can specify the action and category that the current Activity can respond to, open AndroidManifest. xml, and add the following code:


<activity android:name=".SecondActivity">
	<intent-filter>
		<action android:name="com.example.activitytest.ACTION_START" />
		<category android:name="android.intent.category.DEFAULT" />
        <category android:name="com.example.activityest.MY_CATEGORY" />
	</intent-filter>
</activity>

We indicate that the current Activity can respond to com.example.activitytest.ACTION_START This action, and < category > The tag contains 1 additional information. Only < action > And < category > The Activity can respond to the Intent when the contents in the Intent match both action and category specified in the Intent


button1.setOnClickListener {
    val intent = Intent("com.example.activitytest.ACTION_START")
    intent.addCategory("com.example.activityest.MY_CATEGORY")
    startActivity(intent)
}

Using implicit Intent can start not only Activity within your own program, but also Activity of other programs, which makes it possible to share functions among multiple applications. For example, if your application needs to display a web page, you only need to call the browser of the system to open this web page


button1.setOnClickListener {
	val intent = Intent(Intent.ACTION_VIEW)
	intent.data = Uri.parse("https://www.baidu.com")
	startActivity(intent)
}

Passing data using Intent

1. Pass data to the next Activity

The idea of transferring data when starting Activity is very simple. Intent provides a series of overloads of putExtra () methods, which can temporarily store data in Intent, and then take data out of Intent when starting another Activity


button1.setOnClickListener {
    val data = "Hello SecondActivity"
    val intent = Intent(this, SecondActivity::class.java)
    intent.putExtra("extra_data", data)
    startActivity(intent)
}

Then the passed data is fetched in SecondActivity


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.sceond_layout)
    val extraData = intent.getStringExtra("extra_data")
    Log.d("SecondActivity", "extra data is $extraData")
}

2. Return data to the last Activity

There is an startActivityForResult () method in the Activity class that starts Activity and returns the result to the previous Activity when Activity is destroyed. The method takes two parameters:

The first parameter is Intent The second parameter is the request code, which is used to determine the source of the data in the subsequent callback

Modify the button click event code in FirstActivity as follows. Here, startActivityForResult () method is used to start SecondActivity. As long as the request code is only 1 value, 1 is passed in here


button1.setOnClickListener {
    val intent = Intent(this, SecondActivity::class.java)
    startActivityForResult(intent, 1)
}

Next, register the click event for the button in SecondActivity, and add logic to return data to the click event


class SecondActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.sceond_layout)
        button2.setOnClickListener {
            val intent = Intent()
            intent.putExtra("data_return", "Hello FirstActivity")
            setResult(RESULT_OK, intent)
            finish()
        }
    }
}

Here again, an Intent is built, except that this Intent is only used to pass data, and then the setResult () method is called, which specifically returns data to the upper Activity

The setResult () method takes two parameters:

The first parameter is used to return the processing result to the last Activity, which generally uses only two values, RESULT_OK or RESULT_CANCELED The second parameter passes back Intent with data

Since we use the startActivityForResult () method to start SecondActivity, SecondActivity will call back the onActivityResult () method of the last Activity after destruction, so we need to override this method in FirstActivity to get the returned data


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        1 -> if (resultCode == RESULT_OK) {
            val returnedData = data?.getStringExtra("data_return")
            Log.d("FirstActivity", "returned data is $returnedData")
        }
    }
}

The onActivityResult () method takes three parameters:

The first parameter, requestCode, is the request code passed in when we started Activity The second parameter, resultCode, is the processing result we pass in when we return data The third parameter, data, is Intent with the returned data

Since it is possible to call startActivityForResult () in one Activity to start many different Activity, and the data returned by every Activity will be called back to onActivityResult () method, the first thing we should do is to judge the data source by checking the value of requestCode, then judge whether the processing result is successful by the value of resultCode, and finally take the value from data and print it


Related articles: