android app development

Android Intent: Explicit Intent and Implicit 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? now Let’s take a look.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

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:

<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/button_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2"
/>
</LinearLayout>

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:

public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.second_layout);
}
}


Finally, register for SecondActivity in AndroidManifest.xml.

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="This is FirstActivity" >
<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>

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 these 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 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:

button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
}
});

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
figure1

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:

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

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:

button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);
}
});

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 the 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:

button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.activitytest.ACTION_START");
intent.addCategory("com.example.activitytest.MY_CATEGORY");
startActivity(intent);
}
});

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
figure2

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:

<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.activitytest.MY_CATEGORY"/>
</intent-filter>
</activity>

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:

button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.electroniclinic.com"));
startActivity(intent);
}
});

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.

  1. android:host

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

  1. android:port

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

  1. android:path

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

  1. 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:

<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/button_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 3"
/>
</LinearLayout>

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

public class ThirdActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.third_layout);
}
}

Finally, register ThirdActivity in AndroidManifest.xml.

<activity android:name=".ThirdActivity" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>

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
figure3


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 electroniclinic’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.

button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
}
});

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
figure4

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 use 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:

button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String data = "Hello SecondActivity";
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("extra_data", data);
startActivity(intent);
}
});

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:

public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.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);
}
}

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
figure5

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:

button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent, 1);
}
});

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:

public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.second_layout);
Button button2 = (Button) findViewById(R.id.button_2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("data_return", "Hello FirstActivity");
setResult(RESULT_OK, intent);
finish();
}
});
}
}

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:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String returnedData = data.getStringExtra("data_return");
Log.d("FirstActivity", returnedData);
}
break;
default:
}
}

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
figure6


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:

@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("data_return", "Hello FirstActivity");
setResult(RESULT_OK, intent);
finish();
}

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.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button