安卓传递数据怎么接收
时间: 2024-02-05 12:12:14 浏览: 22
在 Android 中传递数据可以通过 Intent 来实现。如果你要接收其他组件或 Activity 传递数据,可以在目标 Activity 中重写 `onCreate` 方法并调用 `getIntent()` 方法获取 Intent 对象,然后从 Intent 对象中获取传递的数据。
例如,如果你想要从上一个 Activity 中传递一个字符串数据到当前 Activity,可以使用以下代码:
在上一个 Activity 中:
```java
String data = "Hello, World!";
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("EXTRA_DATA", data);
startActivity(intent);
```
在目标 Activity 中:
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_target);
Intent intent = getIntent();
String data = intent.getStringExtra("EXTRA_DATA");
// 使用传递过来的数据
// ...
}
```
这里的 `putExtra` 方法将字符串数据放入 Intent 对象中,并使用 `startActivity` 方法启动目标 Activity。在目标 Activity 中,我们使用 `getStringExtra` 方法从 Intent 对象中获取传递的字符串数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)