Android-Bundle认知、和Intent的区别

不时的回过头来看看自己的Andriod学习、实践之路,总发现有些以前不明白的,现在清楚缘由;也会发现一些之前没怎么关注的,现在看到了 ,非常想去深刻了解的。

比如:Bundle

在一个Activity的生命周期中,首先要执行的是onCreate方法

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

在默认情况下,上面红色部分 是 onCreate方法的参数 , 默认执行的方法, 都会自动添加,而这部分一般情况,我都不去关注,你呢?

今天,就来搞清楚这个Bundle的作用,以及和Intent的区别。

 

一、Bundle:A mapping from String values to various Parcelable types

键值对的集合

类继承关系:

java.lang.Object
     android.os.Bundle

Bundle类是一个final类:
public final class Bundle extends Objectimplements Parcelable Cloneable

作用:可以用作是两个Activity间的通讯。

 用法:

①、装载数据:

           Bundle mBundle = new Bundle();   

         mBundle.putString("DataTag""要传过去的数据");  

         Intent intent = new Intent(); 
         intent.setClass(MainActivity.this, Destion.class);  
         intent.putExtras(mBundle);

②、目标Activity解析数据

       Bundle bundle = getIntent().getExtras();  //得到传过来的bundle

       String data = bundle.getString("DataTag");//读出数据

二、Intent的含义和作用 就略了。。。直接上二者比较:

     两个Activity之间传递数据,数据的附加有两种方式:
    一种是直接 intent.putxx();
     另一种是  先bundle.putxx(), 然后再调用public Intent putExtras (Bundle extras)  添加bundle.

     其实两种的本质是一样的。

先看Intent的方法:

public Intent putExtra(String name, boolean value) { 
    if (mExtras == null) { 
        mExtras = new Bundle(); 
    } 
    mExtras.putBoolean(name, value); 
    return this; 

其中mExtras是intent内部定义的一个private Bundle变量。
可以看到,intent其实是调用了bundle相应的put函数,也就是说,intent内部还是用bundle来实现数据传递的,只是封装了一层而已。

而使用Bundle传值的话最后调用的方法:Intent.putExtras(Bundle extras):

public Intent putExtras(Bundle extras) { 
    if (mExtras == null) { 
        mExtras = new Bundle(); 
    } 
    mExtras.putAll(extras); 
    return this; 

可以看到,其实是把之前那个bundle中的数据批量添加到intent内部的bundle中。

其实是和上面的直接用Intent传键值对是一样的原理。

总之呢,Intent旨在数据传递,bundle旨在存取数据,当然intent也提供一部分数据的存取,但比起bundle就显得不专业,不灵活的多

 

 

 

 

 

 

 

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。