1. 数据发送界面:

 1 package com.example.infotransmission;
 2 
 3 import androidx.appcompat.app.AppCompatActivity;
 4 
 5 import android.content.Intent;
 6 import android.os.Bundle;
 7 import android.view.View;
 8 
 9 /**
10  * 实现基本的数据类型的传输,
11  */
12 public class MainActivity extends AppCompatActivity {
13 
14     @Override
15     protected void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.activity_main);
18     }
19 
20     /**
21      * 该方法用于跳转到第二个界面,通过按钮设置onclick
22      * @param view
23      */
24     public void SkipToSecondActivity(View view){
25 
26         // 创建意图对象
27         Intent intent = new Intent(this, SecondaryActivity.class);
28         // 通过调用putExtra来实现数据传递,然后存储类型是键值对
29         intent.putExtra("intKey", 1000);
30         intent.putExtra("booleanKey", true);
31         startActivity(intent);
32     }
33 }

 

2. 数据接收界面(记得新的布局要注册):

 1 package com.example.infotransmission;
 2 
 3 import android.app.Activity;
 4 import android.content.Intent;
 5 import android.os.Bundle;
 6 import android.util.Log;
 7 
 8 import androidx.annotation.Nullable;
 9 
10 public class SecondaryActivity extends Activity {
11     private static final String TAG = "SecondaryActivity";
12 
13     @Override
14     protected void onCreate(@Nullable Bundle savedInstanceState) {
15         super.onCreate(savedInstanceState);
16         setContentView(R.layout.activity_second);
17         // 取得跳转到这个Activity的意图
18         Intent intent = getIntent();
19         // 取值之前首先需要进行判空
20         if (intent != null) {
21             // 调用get'Type'Extra函数
22             // 第二个参数的定义: the value to be returned /if no value of the desire type is stored /with the given name.
23             // 即对于给定的键,如果没有存储想要的类型的值,那么就会返回defaultValue
24             // 对于数组来说,其本身是一个对象,如果数组的长度为空,那就会返回null,所以没有defaultValue
25             int intValue = intent.getIntExtra("intKey", 1);
26             Log.d(TAG, "int value == " + intValue);
27             boolean booleanValue = intent.getBooleanExtra("booleanKey", false);
28             Log.d(TAG, "boolean value == " + booleanValue);
29         }
30     }
31 }

 

posted on 2021-09-22 12:19  EndlessShw  阅读(26)  评论(0编辑  收藏  举报