Android中Bundle

Bundle经常使用在Activity之间或者线程间传递数据,传递的数据可以是boolean、byte、int、long、float、double、string等基本类型或它们对应的数组,也可以是对象或对象数组。
当Bundle传递的是对象或对象数组时,必须实现Serializable或Parcelable接口。
Bundle提供了各种常用类型的putXxx()/getXxx()方法,用于读写基本类型的数据。(各种方法可以查看API)
在activity间传递信息

Bundle bundle = new Bundle();        //得到bundle对象  
bundle.putString("sff", "value值");  //key-"sff",通过key得到value-"value值"(String型)  
bundle.putInt("iff", 175);           //key-"iff",value-175  
intent.putExtras(bundle);            //通过intent将bundle传到另个Activity  
startActivity(intent);

读取数据

Bundle bundle = this.getIntent().getExtras(); //读取intent的数据给bundle对象     
String str1 = bundle.getString("sff"); //通过key得到value     
int int1 = bundle.getInt("iff"); 

线程间传递
通过Handler将带有dundle数据的message放入消息队列,其他线程就可以从队列中得到数据

Message message=new Message();//new一个Message对象     
message.what = MESSAGE_WHAT_2;//给消息做标记  
Bundle bundle = new Bundle(); //得到Bundle对象    
bundle.putString("text1","消息传递参数!");  //往Bundle中存放数据    
bundle.putInt("text2",44);  //往Bundle中put数据    
message.setData(bundle);//mes利用Bundle传递数据  
mHandler.sendMessage(message);//Handler将消息放入消息队列

读取数据
这里用的是Handler的handleMessage(Message msg)方法处理数据

String str1=msg.getData().getString(“text1”);
int int1=msg.getData().getString(“text2”);
Bundle和Intent区别
Bundle只是一个信息的载体,内部其实就是维护了一个Map<String,Object>。

Intent负责Activity之间的交互,内部是持有一个Bundle的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值