zoukankan      html  css  js  c++  java
  • 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就显得不专业。不灵活的多

     

  • 相关阅读:
    前端 CSS
    前端 HTML
    前端 JavaScript 初识
    网络编程——线程池
    网络编程——同一进程中的队列(多线程)
    网络编程——进程间的共享内存
    vue实现前端简易版模糊查询
    封装axios请求拦截器
    关于node中 mysql Client does not support authentication protocol requested by server; consider upgrading MySQL client 解决方法
    封装一个时间方法
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7351060.html
Copyright © 2011-2022 走看看