Android Mobile Application Development Tutorial⑧

  • This article is the eighth article. This article mainly introduces the purpose and components of Intent in detail, as well as the difference between explicit Intent and implicit Intent; then explains how to combine Intent and Bundle to send data to the next active page, and then analyze it in the next page Received request data; then describe the response data returned from the next active page to the previous page, and the returned response data will be parsed by the previous page.
  • This article is a note made during the learning process of the Bilibili tutorial Brain Academy Android tutorial !
  • Most of this article is the knowledge points selected from the video, and some of the text and a small part of the pictures are written by myself.
  • This article follows the previous article "Android Mobile Application Development Tutorial ⑦"
  • Next article "Android Mobile Application Development Tutorial ⑨"

Pass messages between activities

Intent is the most important type of message transfer between activities. Below we will introduce the purpose and components of Intent in detail, as well as the difference between explicit Intent and implicit Intent; and then explain the combination of Intent and Bundle to send data to the next activity page , and then parse the received request data in the next page; then describe the response data returned from the next active page to the previous page, and the previous page parses the returned response data.

One: Explicit Intent and Implicit Intent

The Chinese name of Intent is intent. Simply put, it is to deliver messages. Intent is a bridge for information communication between various components. It can communicate between Activities, between Activity and Service, and between Activity and Broadcast. All in all, Intent is used for communication between Android components, and it mainly completes the following three parts:

  1. Indicate where the communication request comes from, where it goes, and how to go.
  2. The initiator carries the data content required for this communication, and the receiver parses the data from the received intent.
  3. If the initiator wants to judge the processing result of the receiver, the intent is responsible for letting the receiver send back the data content of the response.

The components of an intent are as follows:

There are two ways to express the target of the specified intent object, one is explicit Intent, and the other is implicit Intent.

1.1: Explicit Intents

An explicit Intent directly specifies the source activity and the target activity, which is an exact match.

When constructing an intent object, you need to specify two parameters. The first parameter indicates the source page of the jump, namely "source Activity.this"; the second parameter indicates the page to be redirected, namely "target Activity.class" . There are three specific ways to build intentions:

1. Specify in the Intent constructor, the sample code is as follows:

Intent intent = new Intent(this, ActNextActivity.class); // 创建一个目标确定的意图

2. Call the setClass method of the intent object to specify, the sample code is as follows:

Intent intent = new Intent(); // 创建一个新意图
intent.setClass(this, ActNextActivity.class); // 设置意图要跳转的目标活动

3. Call the setComponent method of the intent object to specify, the sample code is as follows:

Intent intent = new Intent(); // 创建一个新意图
// 创建包含目标活动在内的组件名称对象
ComponentName component = new ComponentName(this, ActNextActivity.class);
intent.setComponent(component); // 设置意图携带的组件信息

 1.2: Implicit Intent

Implicit Intent, does not explicitly specify the target activity to jump to, but only gives an action string for the system to automatically match, which belongs to fuzzy matching.

Usually the app does not want to expose the activity name to the outside, but only gives a pre-defined tag string, so that everyone can follow the convention and find out what is good, and the implicit intent plays the role of tag filtering. This action name tag string can be an action defined by oneself, or an existing system action.

See the table for the value description of common system actions:

The action name can be specified through the setAction method, or the intent object can be directly generated through the constructor Intent(String action). Of course, since actions are fuzzy matches, more detailed paths are sometimes required.

Uri and Category are such path information. Uri data can be specified together when generating objects through the constructor Intent(String action, Uri uri), or can be specified through the setData method (the name of setData is ambiguous, which is actually equivalent to setUri; Category It can be specified by the addCategory method. The reason why add is used instead of the set method is because one intent allows multiple categories to be set, which is convenient for filtering together.

String phoneNo = "12345";
Intent intent = new Intent(); // 创建一个新意图
intent.setAction(Intent.ACTION_DIAL); // 设置意图动作为准备拨号
Uri uri = Uri.parse("tel:" + phoneNo); // 声明一个拨号的Uri
intent.setData(uri); // 设置意图前往的路径
startActivity(intent); // 启动意图通往的活动页面

// 验证是否有activity处理该Intent
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(sendIntent);
}

When called  startActivity() , the system will check all installed applications to determine which applications can handle this kind of Intent (ie: Intent with ACTION_SEND operation and carrying "text/plain" data). If only one app is able to handle it, that app will open immediately and give it the Intent. If more than one Activity accepts the Intent, the system displays a dialog that enables the user to choose which app to use.

 Implicit Intent also uses the concept of filters to filter out those that do not meet the matching conditions, and call the remaining ones that meet the conditions in order of priority. For example, to create an App module, the intent-filter in AndroidManifest.xml is the filter in the configuration file. Like the most common home page activity, MainAcitivity, the filter conditions of action and category are set under the activity node. Among them, android.intent.action.MAIN indicates the entry action of the App, and android.intent.category.LAUNCHER indicates that the App icon is displayed on the desktop. The configuration example is as follows:

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Two: Send data to Activity and return data

2.1 Send data to the next Activity

As mentioned in the previous section, the setData method of the Intent object only specifies the path to the target, not the parameter information carried in this communication. The real parameter information is stored in Extras. Intent overloads a variety of putExtra methods to pass various types of parameters, including basic data types such as integers, doubles, and strings, and even serialized structures such as Serializable.

Just calling the putExtra method is obviously not easy to manage. It is like sending a courier to throw away a package of any size. Not only is it inconvenient to find it, but it is also difficult to know if it is lost.

Therefore, Android introduces the concept of Bundle. Bundle can be understood as a parcel locker or express delivery locker in a supermarket. Packages of all sizes are uniformly accessed by Bundle, which is convenient and safe. The data structure used to store messages inside the Bundle is a Map mapping, which can add or delete elements and determine whether an element exists. If the developer wants to package all the Bundle data, he only needs to call the putExtras method of the intent object once; if he wants to extract all the Bundle data, he only needs to call the getExtras method of the intent object once. See the table for the description of the reading and writing methods of various types of data operated by the Bundle object

 Next, let’s take an example of transferring data between activities. First, use the package to encapsulate the data in the previous activity, stuff the package into the intent object, and then call the startActivity method to jump to the target activity specified by the intent. The complete activity jump code example is as follows:

// 创建一个意图对象,准备跳到指定的活动页面
Intent intent = new Intent(this, ActReceiveActivity.class);
Bundle bundle = new Bundle(); // 创建一个新包裹
// 往包裹存入名为request_time的字符串
bundle.putString("request_time", DateUtil.getNowTime());
// 往包裹存入名为request_content的字符串
bundle.putString("request_content", tv_send.getText().toString());
intent.putExtras(bundle); // 把快递包裹塞给意图
startActivity(intent); // 跳转到意图指定的活动页面

Then in the next activity, obtain the express package that is intended to be carried, take out the parameter information from the package, and display the incoming data in the text view. The following is a code example for the target activity to obtain and display package data:

// 从布局文件中获取名为tv_receive的文本视图
TextView tv_receive = findViewById(R.id.tv_receive);
// 从上一个页面传来的意图中获取快递包裹
Bundle bundle = getIntent().getExtras();
// 从包裹中取出名为request_time的字符串
String request_time = bundle.getString("request_time");
// 从包裹中取出名为request_content的字符串
String request_content = bundle.getString("request_content");
String desc = String.format("收到请求消息:\n请求时间为%s\n请求内容为%s",
request_time, request_content);
tv_receive.setText(desc); // 把请求消息的详情显示在文本视图上

2.2: Return data to the previous Activity

Data transmission is often mutual. The previous page not only sends the request data to the next page, but sometimes also processes the response data of the next page. The so-called response occurs when the next page returns to the previous page. If you only want to send the request data to the next page, just call the startActivity method on the previous page; if you want to process the response data of the next page, you need to process it in multiple steps. The detailed steps are as follows:

Step 1 , the previous page packs the request data, and calls the startActivityForResult method to execute the jump action, indicating that the response data of the next page needs to be processed. The second parameter of this method indicates the request code, which is used to identify the unique sex. An example of the jump code is as follows:

String request = "你吃饭了吗?来我家吃吧";
// 创建一个意图对象,准备跳到指定的活动页面
Intent intent = new Intent(this, ActResponseActivity.class);
Bundle bundle = new Bundle(); // 创建一个新包裹
// 往包裹存入名为request_time的字符串
bundle.putString("request_time", DateUtil.getNowTime());
// 往包裹存入名为request_content的字符串
bundle.putString("request_content", request);
intent.putExtras(bundle); // 把快递包裹塞给意图
// 期望接收下个页面的返回数据。第二个参数为本次请求代码
startActivityForResult(intent, 0);

Step 2, the next page receives and parses the request data, and performs corresponding processing. The receiving code example is as follows:

// 从上一个页面传来的意图中获取快递包裹
Bundle bundle = getIntent().getExtras();
// 从包裹中取出名为request_time的字符串
String request_time = bundle.getString("request_time");
// 从包裹中取出名为request_content的字符串
String request_content = bundle.getString("request_content");
String desc = String.format("收到请求消息:\n请求时间为%s\n请求内容为%s",
request_time, request_content);
tv_request.setText(desc); // 把请求消息的详情显示在文本视图上

Step 3, when the next page returns to the previous page, pack the response data and call the setResult method to return the data package. The first parameter of the setResult method indicates the response code (success or failure), and the second parameter is the intent object carrying the package. An example return code is as follows:

String response = "我吃过了,还是你来我家吃";
Intent intent = new Intent(); // 创建一个新意图
Bundle bundle = new Bundle(); // 创建一个新包裹
// 往包裹存入名为response_time的字符串
bundle.putString("response_time", DateUtil.getNowTime());
// 往包裹存入名为response_content的字符串
bundle.putString("response_content", response);
intent.putExtras(bundle); // 把快递包裹塞给意图
// 携带意图返回上一个页面。RESULT_OK表示处理成功
setResult(Activity.RESULT_OK, intent);
finish(); // 结束当前的活动页面

Step 4: Override the method onActivityResult on the previous page. The input parameters of this method include request code and result code, where the request code is used to determine which jump corresponds to this return, and the result code is used to determine whether the next page is successfully processed. If the next page is successfully processed, unpack the returned data. The code example for processing the returned data is as follows:

// 从下一个页面携带参数返回当前页面时触发。其中requestCode为请求代码,
// resultCode为结果代码,intent为下一个页面返回的意图对象
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{ // 接收返回数据
super.onActivityResult(requestCode, resultCode, intent);
// 意图非空,且请求代码为之前传的0,结果代码也为成功
if (intent!=null && requestCode==0 && resultCode== Activity.RESULT_OK) {
Bundle bundle = intent.getExtras(); // 从返回的意图中获取快递包裹
// 从包裹中取出名叫response_time的字符串
String response_time = bundle.getString("response_time");
// 从包裹中取出名叫response_content的字符串
String response_content = bundle.getString("response_content");
String desc = String.format("收到返回消息:\n应答时间为:%s\n应答内容为:%s",
response_time, response_content);
tv_response.setText(desc); // 把返回消息的详情显示在文本视图上
}
}

Guess you like

Origin blog.csdn.net/qq_64618483/article/details/129936232