IPC机制--使用Bundle进行通信

为什么使用Bundle?

四大组件中的三大组件(Activity, Service, Receiver)都支持在Intent传递Bundle数据,由于Bundle实现了Parcelable接口,所以可以十分方便的在进程间传输,当然我们传输的数据必须能够被序列化,比如基本类型、实现了Parcelable接口的对象、实现了Serializable接口的对象以及一些Android所支持的特殊对象。

如何利用Bundle进行通信?

1. 传输Bundle支持的数据类型

package com.example.no_clay.messagertest.Data;


import android.os.Parcel;
import android.os.Parcelable;

import java.io.Serializable;

/**
 * Created by no_clay on 2017/2/26.
 */

public class User implements Serializable, Parcelable{

    private static final long serialVersionUID = -2534337785069283741L;
    String name;
    String id;

    public User(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(id);
    }

    protected User(Parcel in) {
        name = in.readString();
        id = in.readString();
    }


    public static final Creator<User> CREATOR = new Creator<User>() {
        @Override
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        @Override
        public User[] newArray(int size) {
            return new User[size];
        }
    };
}

2. 将数据放置到Bundle中

User user = new User("测试玩家", "num123");
                Bundle bundle = new Bundle();
                bundle.putParcelable("user", user);
                Intent intent = new Intent(this, BundleActivity.class);
                intent.putExtra("user", bundle);
                startActivity(intent);

3. 在目标进程组件中将Bundle中的数据还原

        Bundle data = getIntent().getBundleExtra("user");
        User user = data.getParcelable("user");
        Log.d(TAG, "onCreate: userName = " + user.getName());
        Log.d(TAG, "onCreate: id = " + user.getId());

测试结果

两个处在不同的进程:
这里写图片描述

进程间通信:

02-26 21:07:44.426 17850-17850/? D/BundleActivity: onCreate: userName = 测试玩家
02-26 21:07:44.426 17850-17850/? D/BundleActivity: onCreate: id = num123

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值