首页 > android Intent 本身就可以附加数据 为何还用 bundle?

android Intent 本身就可以附加数据 为何还用 bundle?

如题,intent 附加数据已经足够强大,为何需要bundle

感谢各位的回应!
针对一楼的回答,然后看了下源码,发现Bundle内部其实就是维护了一个Map<String,Object> 而已


因为Intent内部是持有一个Bundle对象的,看一下putExtra()方法的源码就知道了

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

1.intent附加的数据强大吗,只有一些基本类型而已,一到自定义对象的时候就萎了
2.看看bundle是什么:A mapping from String values to various Parcelable types.
鄙人认为,这个bundle就是个hash表的奇行种,不管你用不用intent,人家已经在哪里好久了,所以不存在“intent 附加数据已经足够强大,为何需要bundle”这种问题。


Bundle在Activity之间传递数据,传递的数据可以是boolean、byte、int、long、float、double、string等基本类型或它们对应的数组,也可以是对象或对象数组。当Bundle传递的是对象或对象数组时,必须实现Serializable 或Parcelable接口。由此看出bundle比intent更强大

Intent是Android的一种机制,

startActivity(Intent intent);
startService(Intent service);
sendBroadcast(Intent intent);
bindService(Intent service, ServiceConnection conn, int flags);

借助Android提供的上述API,我们可以把intent发送给Android,Android收到后会做相应的处理,启动Activity,发送广播给BroadcastReceiver,启动Service或者绑定Service。
Intent还可以附加各种数据类型,其中就包括BundleIntent.putExtra(String name, Bundle value)

而Bundle仅仅是一种键值对数据结构,存储字符串键与限定类型值之间映射关系。
虽然如此,但仍有应该使用bundle的情景(目前想到2个,应该还有更多):

使用Bundle的场景1:在设备旋转时保存数据

public class CustomView extends View {
    // 自定义View旋转时保存数据
    @Override
    protected Parcelable onSaveInstanceState() {
        super.onSaveInstanceState();
        Bundle bundle = new Bundle();
        bundle.put...
        return bundle;
    }
    
public class CustomActivity extends Activity {
    // Activity旋转时保存数据
    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.put...
    }

使用Bundle的场景2:从Fragment传递数据到另一Fragment

比如,某个界面由Fragment搭建,其中包含一个按钮,点击按钮弹出一个DialogFragment,
最便捷的方式就是通过Fragment.setArguments(args)传递参数。

所以,Bundle是不可替代的。

【热门文章】
【热门文章】