Android-intent传递数

先来复习一下序列化

https://www.jianshu.com/p/c2a6161f1546

Parcelable是Android为我们提供的序列化的接口,Parcelable相对于Serializable的使用相对复杂一些,但Parcelable的效率相对Serializable也高很多,这一直是Google工程师引以为傲的,有时间的可以看一下Parcelable和Serializable的效率对比 Parcelable vs Serializable 号称快10倍的效率

传递实际上是使用了binder机制,binder机制会将Parcel序列化的数据写入到一个共享内存中,读取时也是binder从共享内存中读出字节流,然后Parcel反序列化后使用。这就是Intent或Bundle能够在activity或者跨进程通信的原理。

一、Intent传递数据

intent.putExtra()
传递的数据都需要支持序列化

二、Intent传递数据大小限制

为什么 Intent 传值会有大小限制。
  • 应用进程在启动 Binder 机制时会映射一块 1M 大小的内存,所有正在进行的 Binder 事务共享这 1M 的缓冲区。当使用 Intent 进行 IPC 时申请的缓存超过 1M - 其他事务占用的内存时,就会申请失败抛 TransactionTooLargeException 异常了。
  • 简单来说,我们上面提到了Parcel机制使用了一个共享内存,这个共享内存就叫Binder transaction buffer,这块内存有一个大小限制,目前是1MB,而且共用的,当超过了这个大小就会报错。
  • 也就是说不仅仅是一次性传递大数据会出问题,当同时传递很多数据,尽管每个都不超过1MB,但是总大小超过1MB也会出错。
如何绕开这个限制呢?
  • 通过 AIDL 使用 Binder 进行 IPC 就不受这个限制,具体代码如下:
Bundle bundle = new Bundle();
bundle.putBinder("binder", new IRemoteGetBitmap.Stub() {
    @Override
    public Bitmap getBitMap() throws RemoteException {
        return mBitmap;
    }
});
intent.putExtras(bundle);
为什么通过 putBinder 的方式传 Bitmap 不会抛 TransactionTooLargeException 异常?
  • 当我们用Intent传输过大数据时,一般logcat会报出TransactionTooLargeException错误,谷歌官方对这个错误的描述如下:
The Binder transaction failed because it was too large.
During a remote procedure call, the arguments and the return value of the call are transferred as
Parcel objects stored in the Binder transaction buffer. If the arguments or the return value are too
large to fit in the transaction buffer, then the call will fail and TransactionTooLargeException
will be thrown.

The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all
transactions in progress for the process. Consequently this exception can be thrown when there
are many transactions in progress even when most of the individual transactions are of moderate size.

There are two possible outcomes when a remote procedure call throws TransactionTooLargeException.
Either the client was unable to send its request to the service (most likely if the arguments were
too large to fit in the transaction buffer), or the service was unable to send its response back to
the client (most likely if the return value was too large to fit in the transaction buffer). It is
not possible to tell which of these outcomes actually occurred. The client should assume that a
partial failure occurred.

The key to avoiding TransactionTooLargeException is to keep all transactions relatively small.
Try to minimize the amount of memory needed to create a Parcel for the arguments and the return
value of the remote procedure call. Avoid transferring huge arrays of strings or large bitmaps.
If possible, try to break up big requests into smaller pieces.

If you are implementing a service, it may help to impose size or complexity contraints on the
queries that clients can perform. For example, if the result set could become large, then don't
allow the client to request more than a few records at a time. Alternately, instead of returning
all of the available data all at once, return the essential information first and make the client
ask for additional information later as needed.
  • 这个问题,我们先来看下,底层在 IPC 时是怎么把 Bitmap 写进 Parcel 的。
Android - 28 Bitmap.cpp
static jboolean Bitmap_writeToParcel(JNIEnv* env, jobject, ...) {
    // 拿到 Native 的 Bitmap                                
    auto bitmapWrapper = reinterpret_cast(bitmapHandle);
    // 拿到其对应的 SkBitmap, 用于获取 Bitmap 的像素信息
    bitmapWrapper->getSkBitmap(&bitmap);

    int fd = bitmapWrapper->bitmap().getAshmemFd();
    if (fd >= 0 && !isMutable && p->allowFds()) {
        // Bitmap 带了 ashmemFd && Bitmap 不可修改 && Parcel 允许带 fd
        // 就直接把 FD 写到 Parcel 里,结束。
        status = p->writeDupImmutableBlobFileDescriptor(fd);
        return JNI_TRUE;
    }

    // 不满足上面的条件就要把 Bitmap 拷贝到一块新的缓冲区
    android::Parcel::WritableBlob blob;
    // 通过 writeBlob 拿到一块缓冲区 blob
    status = p->writeBlob(size, mutableCopy, &blob);

    // 获取像素信息并写到前面拿到缓冲区 blob
    const void* pSrc =  bitmap.getPixels();
    if (pSrc == NULL) {
        memset(blob.data(), 0, size);
    } else {
        memcpy(blob.data(), pSrc, size);
    }
}
  • 接下来我们看一下 writeBlob 是怎么获取缓冲区的(注意虽然方法名写着 write , 但是实际往缓冲区写数据是在 writeBlob 方法执行之后处理的)
Android - 28 Parcel.cpp
// Maximum size of a blob to transfer in-place.
static const size_t BLOB_INPLACE_LIMIT = 16 * 1024;

status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
{
    if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
        // 如果不允许带 fd ,或者这个数据小于 16K
        // 就直接在 Parcel 的缓冲区里分配一块空间来保存这个数据
        status = writeInt32(BLOB_INPLACE);
        void* ptr = writeInplace(len);
        outBlob->init(-1, ptr, len, false);
        return NO_ERROR;
    }

    // 另外开辟一个 ashmem,映射出一块内存,后续数据将保存在 ashmem 的内存里
    int fd = ashmem_create_region("Parcel Blob", len);
    void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    ...
    // parcel 里只写个 fd 就好了,这样就算数据量很大,parcel 自己的缓冲区也不用很大
    status = writeFileDescriptor(fd, true /*takeOwnership*/);
    outBlob->init(fd, ptr, len, mutableCopy);
    return status;
}
  • 通过上面的分析,我们可以看出,同一个 Bitmap 写入到 Parcel 所占的缓冲区大小和 Pacel 的 allowFds 有关。
  • 直接通过 Intent 传 Bitmap 容易抛 TransactionTooLargeException 异常,就是因为 Parcel 的 allowFds = false,直接把 Bitmap 写入缓冲区占用了较大的内存。
  • 接下来,我们来看一下,allowFds 是什么时候被设置成 false 的呢:
// 启动 Activity 执行到 Instrumentation.java 的这个方法
public ActivityResult execStartActivity(..., Intent intent, ...){
  ...
  intent.prepareToLeaveProcess(who);
  ActivityManager.getService().startActivity(...,intent,...)
}

// Intent.java
public void prepareToLeaveProcess(boolean leavingPackage) {
 // 这边一层层传递到最后设置 Parcel 的 allowfds
  setAllowFds(false);
  ....
}

总结一下:较大的 bitmap 直接通过 Intent 传递容易抛异常是因为 Intent 启动组件时,系统禁掉了文件描述符 fd 机制 , bitmap 无法利用共享内存,只能拷贝到 Binder 映射的缓冲区,导致缓冲区超限, 触发异常; 而通过 putBinder 的方式,避免了 Intent 禁用描述符的影响,bitmap 写 parcel 时的 allowFds 默认是 true , 可以利用共享内存,所以能高效传输图片。

你可能感兴趣的:(Android-intent传递数)