安卓基础知识:Intent解析

定义

用于描述应用的动作及其对应数据

作用

①指定当前组件需要做的动作
②在不同组件之间传递数据(Activity、Service、BroadcastReceiver)

使用

指明组件要完成的动作

显式意图
在intent初始化时直接显式传入所需数据
隐式意图
通过action、category、data匹配隐式获取到AndroidManifest中设置好的内容
具体使用在Activity分析中用到

不同组件传递数据

使用方法

putExtra()、Bundle

可传递的数据类型

①8大基本数据类型
②Intent、Bundle
③Serializable对象、Parcelable对象、CharSequence类型
④ArrayList,泛型参数类型为<Integer>、<? Extends Parcelable>、<Charsequence>、<String>

具体使用

在当前Activity中将传递的数据存到Intent中,再在新启动的Activity中取出Intent获取数据

putExtra:

// a. 创建Intent对象(显示Intent)
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);     

// b. 通过putExtra()方法传递一个字符串到SecondActivity;
// putExtra()方法接收两个参数:第一个是键,第二个是值(代表真正要传递的数据)
intent.putExtra("data","I come from FirstActivity");

// c. 启动Activity
startActivity(intent);

数据获取:

// 2. 数据取出(在被启动的Activity中)
// a. 获取用于启动SecondActivit的Intent
Intent intent = getIntent();
// b. 调用getStringExtra(),传入相应的键名,就可得到传来的数据
// 注意数据类型 与 传入时保持一致
String data = intent.getStringExtra("data");

bundle

// 1. 数据传递
// a. 创建Intent对象(显示Intent)
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);     

// b. 创建bundle对象
Bundle bundle = new Bundle();

// c. 放入数据到Bundle
bundle.putString("name", "carson");
bundle.putInt("age", 28);

// d. 将Bundle放入到Intent中
intent.putExtras(bundle);

// e. 启动Activity
startActivity(intent);

数据获取:

// 2. 数据取出(在被启动的Activity中)
// a. 获取用于启动SecondActivit的Intent
Intent intent = getIntent();

// b. 通过Intent获取bundle
Bundle bundle = intent.getExtras();

// c. 通过bundle获取数据传入相应的键名,就可得到传来的数据
// 注意数据类型 与 传入时保持一致
String nameString = bundle.getString("name");
int age = bundle.getInt("age");
两种方式的区别

①当涉及连续传递数据时,使用putExtra需要写多次获取、写入数据才能完成操作;而Bundle只需要取出再写入即可
②可传递的内容:putExtra不可传递对象,而Bundle可以通过putSerializable传递实现了Serializable接口的对象。(序列化操作在之前有解析,Parcelable和Serializable都可以)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔幻音

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值