Android Intent: Explicit Intent and Implicit Intent

Android Intent

Use Android Intent to shuttle between activities

Android intent:- Is it too simple to have only one activity? Yes, your pursuit should be higher. No matter how many you want to create For each activity, the method is the same as that described in the previous section. The only problem is that you click on the application icon in the launcher The target will only enter the main activity of the application, so how can I jump from the main activity to other activities? Let’s have one now Let’s take a look.



Use explicit Android Intent

You should already be familiar with the process of creating an activity, then we will quickly re-start in the ActivityTest project Create an event. Create a new second_layout.xml layout file, the code is as follows:

We still define a button, and Button 2 is displayed on the button. Then create a new activity SecondActivity inherited from Activity, the code is as follows:

Finally, register for SecondActivity in AndroidManifest.xml.

Since SecondActivity is not the main activity, there is no need to configure the content in the <intent-filter> tag, register the activity The code for moving is much simpler. Now that the second activity has been created, the remaining question is how to start this Two activities, here we need to introduce a new concept, Intent. Android intent is an important way of interaction between components in the Android program, it can not only indicate the current group The actions that the software wants to perform can also pass data between different components. Android intent can generally be used to start activities, start Service, and broadcasting and other scenes, because of the concept of service, broadcasting, etc., you haven’t covered it yet, so our vision in this article It is undoubtedly locked in the start activity.


The usage of Android intent can be roughly divided into two types, explicit Android intent and implicit Android intent, let’s take a look at explicit Android intent first how to use. Android intent has multiple constructor overloads, one of which is Intent(Context packageContext, Class<?> cls). This constructor receives two parameters, the first parameter Context requires a context to start the activity, the second The parameter Class is to specify the target activity you want to start, and the “intent” of the Android intent can be constructed through this constructor. Then how should we use this Intent? A startActivity() method is provided in the Activity class. This method It is specially used to start the activity. It receives an Intent parameter. Here we pass the constructed Intent to startActivity() The method can start the target activity.

Modify the click event of the button in FirstActivity, the code is as follows:

We first constructed an Android intent, passed in FirstActivity.this as the context, and passed in SecondActivity.class As the target activity, our “intent” is very obvious, that is, to play on the basis of FirstActivity. Open this activity SecondActivity. Then execute this Android intent through the startActivity() method. Re-run the program and click the button on the FirstActivity interface. The result is shown in Figure 1.

Android Intent
fig1

As you can see, we have successfully started the SecondActivity activity. If you want to go back to the previous event How to do it? Very simple, press the Back key to destroy the current activity and return to the previous activity. Using this method to start an activity, the “intent” of the Android intent is very obvious, so we call it an explicit Android intent.

Use Implicit Android Intent

Compared to explicit Android intent, implicit Android intent is a lot more implicit, it does not clearly indicate which activity we want to start Instead, it specifies a series of more abstract action and category information, and then the system analyzes this Android intent. And help us find suitable activities to start. What is a suitable activity? Simply put, it can respond to our implicit Intent activity, so currently What kind of implicit Android intent can SecondActivity respond to? Um, I don’t seem to be able to respond to anything, but it’s

There will be soon. By configuring the content of <intent-filter> under the <activity> tag, you can specify the action that the current activity can respond to And category, open AndroidManifest.xml and add the following code:

In the <action> tag, we indicate that the current activity can respond to com.example.activitytest.ACTION_

The START action and the <category> tag contains some additional information, which more accurately indicates the current activity The category that may be included in the responding Android intent. Only the content in <action> and <category> can match When matched with the action and category specified in the Android intent, this activity can respond to the Android intent. Modify the click event of the button in FirstActivity, the code is as follows:

As you can see, we used another constructor of Android intent to directly pass in the string of action, the table We want to start an activity that responds to the action com.example.activitytest.ACTION_START. Before that Didn’t it say that <action> and <category> must match at the same time to respond? Why didn’t I see where there is a designation What about category? This is because android.intent.category.DEFAULT is a default category, in the call, This category will be automatically added to the Intent in the startActivity() method. Re-run the program, click the button on the FirstActivity interface, you also successfully start SecondActivity Up. The difference is that this time you use the implicit Android intent method to start, indicating that we configure under the <activity> tag The contents of the set action and category have taken effect! Only one action can be specified in each Android intent, but multiple categories can be specified. Currently, we only have A default category, so let’s add another one now. Modify the click event of the button in FirstActivity, the code is as follows:

You can call the addCategory() method in the Intent to add a category, where we specify a custom Meaning category, the value is com.example.activitytest.MY_CATEGORY. Now run the program again, click the button on the FirstActivity interface, you will find that the program has crashed! This This is the first time you have encountered a program crash, and you may be a little helpless. Don’t worry, most of the crashes are actually very A good solution, as long as you are good at analysis. Check the error log on the LogCat interface, you will see the error shown in Figure2 information.

Android Intent
fig2


The error message reminds us that no activity can respond to our Android intent. Why? This is because We just added a category to the Intent, and there is no sound in the <intent-filter> tag of SecondActivity It can respond to this category, so there is no activity that can respond to the Intent. Now, we Add another category declaration in <intent-filter>, as shown below:

Re-run the program again and you will find that everything is normal.

More usage of Implicit android Intent

In the previous section, you have mastered the way to start activities through implicit android intents, but in fact there are more implicit android intents You need to understand the content of. In this section, we will introduce it. Using implicit Android intent, we can not only start the activities in our own program, but also start the activities of other programs, This makes it possible to share functions between multiple Android applications. For example, you need to display in your application A web page, at this time you don’t need to implement a browser yourself (in fact, it’s unlikely), but just call The system browser can open this webpage. Modify the code of the button click event in FirstActivity as follows:

Here we first specify that the Android intent action is Intent.ACTION_VIEW, which is an Android system The constant value of the set action is android.intent.action.VIEW. Then through the Uri.parse () method, a URL The string is parsed into a Uri object, and then the setData() method of the Intent is called to pass this Uri object in. Re-run the program and click the button on the FirstActivity interface to see that the system browser is opened. In the above code, you may be unfamiliar with the setData() part, which we have not mentioned before. This method is actually not complicated, it receives a Uri object, mainly used to specify the current Android intent is operating data, and These data are usually passed into the Uri.parse() method in the form of strings and parsed. Corresponding to this, we can also configure a <data> tag in the <intent-filter> tag to more accurately indicate Determine what type of data the current activity can respond to. The following contents can be configured in the <data> tag.

1.android:scheme

Used to specify the protocol part of the data, such as the http part in the above example.

2.android:host

Used to specify the host name part of the data, such as the www.programmigdigest.com part in the above example.

3.android:port

Used to specify the port part of the data, usually immediately after the host name.

4.android:path

Used to specify the part after the host name and port, such as the content following the domain name in a URL.

5.android:mimeType

Used to specify the type of data that can be processed, allowing the use of wildcards to specify. Only when the content specified in the <data> tag is exactly the same as the Data carried in the Intent, the current activity can respond The Android intent. However, generally, too much content is not specified in the <data> tag. For example, in the browser example above, only You need to specify android:scheme as http, then you can respond to all intents of the http protocol. In order to allow you to understand more intuitively, let’s create an activity by ourselves so that it can respond to opening webpages Android intent.

Create a new third_layout.xml layout file, the code is as follows:



Then create a new activity ThirdActivity inherited from Activity, the code is as follows:

We have configured the action that the current activity can respond to in the <intent-filter> of ThirdActivity. Intent.ACTION_VIEW constant value, and category is undoubtedly specified the default category value, and  In the <data> tag, we specify that the data protocol must be http protocol through android:scheme, so ThirdActivity It should be able to respond to an Android intent to open a web page just like the browser. Let’s run the program to try it out in Click the button on the FirstActivity interface, and the result is shown in Figure3.

Android Intent
fig3

As you can see, the system automatically pops up a list showing all programs that can respond to this Intent. Point Clicking on Browser will open the browser as before and display programmingdigest’s homepage, and if you click on ActivityTest, then Will start ThirdActivity. It should be noted that although we have declared that ThirdActivity can respond to open web pages Intent, but in fact this activity does not have the function of loading and displaying web pages, so try not to do it in real projects To do this kind of behavior that may mislead users, otherwise it will make users have a negative impression of our application. In addition to the http protocol, we can also specify many other protocols, such as geo to indicate geographic location, tel to indicate dial number. The following code shows how to call the system dial interface in our program.

The first action that specifies the Android intent is Intent.ACTION_DIAL, which is another built-in action of the Android system. Made. Then the protocol is tel and the number is 10086 in the data part. Re-run the program, in FirstActivity Click the button once on the interface, and the result is shown in Figure4.

Android Intent
fig4


Pass Data to the next Activity using Android Intent

After studying in the previous sections, you already have a certain understanding of Android intent. But so far, we are just Simply using Android intent to start an activity. In fact, Android intent can also pass data when starting an activity. We Let’s take a look. The idea of ​​passing data when starting an activity is very simple. Android intent provides a series of overloads of the putExtra() method. In order to temporarily store the data we want to transmit in the Intent, after starting another activity, we only need to transfer the data from Just remove it from the Android intent. For example, there is a string in FirstActivity, and now I want to pass this string to In SecondActivity, you can write like this:

Here we still use explicit Android intent to start SecondActivity and pass it through the putExtra() method A string. Note that the putExtra() method receives two parameters, the first parameter is the key, which is used later from the Intent The second parameter is the real data to be passed. Then we take out the passed data in SecondActivity and print it out. The code is as follows:

First you can get the Intent used to start SecondActivity through the getIntent() method, and then call GetStringExtra() method, pass in the corresponding key value, you can get the passed data. Here because we are passing String, so use the getStringExtra() method to get the passed data, if the passed integer data, use The getIntExtra() method, if the Boolean data is passed, use the getBooleanExtra() method, and so on. Re-run the program, click on the button on the FirstActivity interface to jump to SecondActivity, view LogCat print information, as shown in Figure5.

Android Intent
fig5

As you can see, we successfully got the data passed from FirstActivity in SecondActivity.


Return data to the previous activity using Android Intent

Since data can be passed to the next activity, can it be returned to the previous activity? The answer is yes of. But the difference is that you only need to press the Back key to return to the previous activity, and there is no one to start Activity Intent to pass data. By consulting the documentation, you will find that there is also a startActivityForResult() in Activity The method is also used to start the activity, but this method expects to return a result to the previous activity when the activity is destroyed move. There is no doubt that this is what we need. The startActivityForResult() method receives two parameters, the first parameter is still Intent, and the second parameter is request Code, used to determine the source of the data in subsequent callbacks. Let’s take a real fight and modify the buttons in FirstActivity The click event, the code is as follows:

Here we use the startActivityForResult() method to start SecondActivity, as long as the request code is one The only value is fine, and 1 is passed in here. Next, we register the click event for the button in SecondActivity, and Add logic to return data in the click event, the code is as follows:

As you can see, we still built an Intent, but this Android intent is only used to transfer data. It does not specify any “intent”. Then the data to be transferred is stored in the Intent, and then setResult() is called method. This method is very important, it is specifically used to return data to the previous activity. setResult() method receives two Parameters, the first parameter is used to return the processing result to the previous activity, generally only RESULT_OK or RESULT_CANCELED these two values, the second parameter is to pass back the Intent with data, and then call The finish() method is used to destroy the current activity. Since we use the startActivityForResult() method to start SecondActivity, in SecondActivity After it is destroyed, the onActivityResult() method of the previous activity will be called back, so we need to reload in FirstActivity Write this method to get the returned data, as shown below:

The onActivityResult() method takes three parameters, the first parameter requestCode, which is passed when we start the activity The incoming request code. The second parameter, resultCode, is the processing result passed in when we return the data. The third parameter data, It carries the Intent that returns the data. Since it is possible to call the startActivityForResult() method in an activity to start Move many different activities, the data returned by each activity will be called back to the onActivityResult() method, so The first thing we need to do is to determine the source of the data by checking the value of requestCode. Make sure the data is from After SecondActivity returns, we then use the value of resultCode to determine whether the processing result is successful. Finally from Get the value in data and print it out, thus completing the work of returning data to the previous activity. Re-run the program, click the button on the FirstActivity interface to open SecondActivity, and then Click the Button 2 button on the SecondActivity interface to return to FirstActivity, then check the print information of LogCat, such as As shown in Figure6.

Android Intent
fig6

As you can see, SecondActivity has successfully returned data to FirstActivity. At this time, you may ask, if the user in SecondActivity is not by clicking the button, but by pressing The Back key returns to FirstActivity, so can’t the data be returned? Yes, but this situation is still easy to handle Yes, we can solve this problem by rewriting the onBackPressed() method, the code is as follows:

In this case, when the user presses the Back key, the code in the onBackPressed() method will be executed. We are here Just add the logic to return the data.



Related Article:

Android Activity: Basic usage of Android activities, Toast Message, Menu

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: