Activity analysis of the four major components of Android (below)

1. Activity review

In the Activity analysis of the four major components of Android (on) , we have already talked about the startup method , life cycle and startup mode of the Activity . In this section, let's talk about the two knowledge points of passing parameters between activities and how to start system activities . The transfer of parameters between activities includes the use of Intent to transfer parameters , the use of Bundle to transfer parameters and the transfer of complex data .

Two, data transfer between activities

2.1, use Intent to transfer data

Using Intent to transfer data is mainly to call the Intent.putExtra() method. This method has two parameters. The first parameter is name and the second parameter is value. The type of value is as follows:

Intent method
The specific code for transferring data is as follows :

// 1、利用 Intent 传递数据
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("str", "Android 开发");  // 传递 String
intent.putExtra("flag", true);
startActivity(intent);

The transmitted code has been written, so how to receive it? We can use the getIntent() method to receive data in SecondActivity, as shown below:

TextView params = findViewById(R.id.tv_params);
// 接收数据
String str = getIntent().getStringExtra("str");
// 这里的 false 是默认值的意思,如果没有接收到 flag 的值就是 false
boolean flag = getIntent().getBooleanExtra("flag", false);
if (flag) {
    
    
    params.setText(str);
} else {
    
    
    params.setText("没有接受到数据");
}

Let's look at the effect:

Transfer data

2.2. Use Bundle to transfer data

Using Bundle to transfer data is mainly to use Bundle to store the data to be transferred first, and then transfer the Bundle data set to the Activity that needs to be received. Let's look at the transferred code:

// 2、利用 Bundle 传递数据
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("str", "Android 开发");
bundle.putBoolean("flag", true);
intent.putExtra("myBundle", bundle);	
startActivity(intent);

Receiving the Bundle is also very simple, we only need to call the getIntent().getBundleExtra() method. Let’s look at the code:

Bundle bundle = getIntent().getBundleExtra("myBundle");
if (bundle != null) {
    
    
    String str = bundle.getString("str");
    boolean flag = bundle.getBoolean("flag");
    if (flag) {
    
    
        params.setText(str);
    } else {
    
    
        params.setText("没有接受到数据");
    }
}

The effect of Bundle passing data and Intent passing data is exactly the same, but the writing is a little different.

2.3, the transfer of complex data between activities

The above two methods can pass any basic type of data, but if you want to pass a complex data (such as an object), what should you do? Android provides us with two methods to pass complex types of data:

2.3.1. Implement the Serilziable interface for the classes that need to be passed

Here we create a UserInfo class to implement the Serilziable interface, the specific code is as follows:

import java.io.Serializable;

public class UserInfo implements Serializable {
    
    
    public String username;
    public int age;
    public int gender;
}

The code passed is as follows:

// 3、复杂类型的数据传递  实现 Serializable 接口
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
UserInfo userInfo = new UserInfo();
userInfo.username = "Bob";
userInfo.age = 25;
userInfo.gender = 1;
intent.putExtra("userInfo", userInfo);
startActivity(intent);

To receive the Serializable object, we need to call the getIntent().getSerializableExtra() method, let’s look at the code:

UserInfo userInfo = (UserInfo) getIntent().getSerializableExtra("userInfo");
if (userInfo != null) {
    
    
    String str = "名字:" + userInfo.username + " " + "年龄:" + userInfo.age + " " + "性别:" +
            (userInfo.gender == 1 ? "男" : "女");
    params.setText(str);
}

Let's look at the effect:

Object data

2.3.2, implement the Parceable interface for the classes that need to be passed

Here we create an Order class to implement the Parceable interface. We only need to rewrite the describeContents method and the writeToParcel method. The Creator is automatically generated. The specific code is as follows:

public class Order implements Parcelable {
    
    

    public String address;
    public boolean isReceived;
    public int count;

    public Order() {
    
    
    }

    protected Order(Parcel in) {
    
    
        address = in.readString();
        isReceived = in.readByte() != 0;
        count = in.readInt();
    }

    public static final Creator<Order> CREATOR = new Creator<Order>() {
    
    
        @Override
        public Order createFromParcel(Parcel in) {
    
    
            return new Order(in);
        }

        @Override
        public Order[] newArray(int size) {
    
    
            return new Order[size];
        }
    };

    @Override
    public int describeContents() {
    
    
        // 只有当对象中存在文件描述符的时候才需要返回 1,通常情况下返回 0 即可
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
    
    
        dest.writeString(address);
        dest.writeBoolean(isReceived);
        dest.writeInt(count);
    }
}

The code passed is as follows:

// 4、复杂类型的数据传递  实现 Parcelable 接口
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Order order = new Order();
order.address = "测试地址";
order.isReceived = true;
order.count = 5;
intent.putExtra("order", order);
startActivity(intent);

To receive the Parcelable object, we need to call the getIntent().getParcelableExtra() method, let’s look at the code:

Order order = getIntent().getParcelableExtra("order");
if (order != null) {
    
    
    String str = "地址:" + order.address + " " + "购买数量:" + order.count + " " + "是否已经确认收货:" +
            (order.isReceived ? "是" : "否");
    params.setText(str);
}

Let's look at the effect:

Complex data

2.4, Activity data return

When the second Activity needs to return data to the first Activity, we only need to start the second Activity through the startActivityForResult() method. When the second Activity is closed, the Android system will call back the first one. Activity's onActivityResult() method, in this method we can get some data returned by the second Activity.

The specific code of MainActivity is as follows:

public class MainActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                // 5、Activity 数据回传
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivityForResult(intent, 1000);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
    
        super.onActivityResult(requestCode, resultCode, data);

        String backData = data.getStringExtra("back_data");
        Log.e("MainActivityTag", "requestCode:" + requestCode + " " + "resultCode:" + resultCode + " " +
                "回传的数据:" + backData);
    }
}

The specific code of SecondActivity is as follows:

public class SecondActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Intent intent = new Intent();
        intent.putExtra("back_data", "回传数据是。。。。。。。。");
        setResult(RESULT_OK, intent);
    }
}

The result is as follows:

Insert picture description here

Three, start the activity of the system

Activity components commonly used in the Android system include making calls , sending text messages, and turning on the camera . The startup methods are:

  • intent.setAction(Intent.ACTION_DIAL);
  • intent.setAction(Intent.ACTION_SENDTO)
  • intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE)

The specific code is as follows:

  1. dial number
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_DIAL);
    startActivity(intent);
    
  2. send messages
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SENDTO);
    Uri smsToUri = Uri.parse("smsto:" + 10086);
    intent.setData(smsToUri);
    intent.putExtra("sms_body", "短信内容");
    startActivity(intent);
    
  3. turn on a camera
    Intent intent = new Intent();
    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivity(intent);
    

The specific effects are as follows:
Demo

Four, summary

So far, we have talked about the five startup methods , life cycle , four startup modes , data transfer between activities, and how to start system Activity components .

Guess you like

Origin blog.csdn.net/weixin_38478780/article/details/108826674