码迷,mamicode.com
首页 > 移动开发 > 详细

Android-Bundle认知、和Intent的差别

时间:2017-08-12 18:58:06      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:data   数据   ext   继承   rri   create   return   部分   也会   

不时的回过头来看看自己的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就显得不专业。不灵活的多

 

 

 

 

 

 

 

 

 

Android-Bundle认知、和Intent的差别

标签:data   数据   ext   继承   rri   create   return   部分   也会   

原文地址:http://www.cnblogs.com/mfmdaoyou/p/7351060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!