其他
binder传递大数据:AIDL 如何分片传输大量 Parcelable 数据
本文作者
作者:孙强Jimmy
链接:
https://juejin.cn/post/7304635193418481674
本文由作者授权发布。
本文针对 AIDL 跨进程传输大量 Parcelable 数据所产生的问题总结出一套分片传输的解决方案,并分析了一下其实现的原理。
下面就来讲述一个分片传输的处理方案,来解决这类数据过大的问题。
import android.app.Notification;
interface IAIDLTest {
List<Notification> getNotifications();
}
public class AIDLTestService extends Service {
private final IBinder mService = new IAIDLTest.Stub() {
@Override
public List<Notification> getNotifications() {
List<Notification> notifications = new ArrayList<>();
for (int i = 0; i < 50; i++) { // 先构建 50 条数据看效果,后面再作增加
notifications.add(new Notification.Builder(AIDLTestService.this,
"CHANNEL_ID")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(Icon.createWithResource(AIDLTestService.this,
R.drawable.ic_avatar))
.setContentTitle("标题文本" + i)
.setContentText("正文文本" + i)
.setContentIntent(NotificationUtils.createActivityPendingIntent(AIDLTestService.this, "AIDL 测试" + i))
.setAutoCancel(true)
.addAction(0, "按钮 1",
NotificationUtils.createActivityPendingIntent(AIDLTestService.this, "按钮 1" + i))
.addAction(0, "按钮 2",
NotificationUtils.createReceiverPendingIntent(AIDLTestService.this, "按钮 2" + i))
.build());
}
return notifications;
}
};
@Override
public IBinder onBind(Intent intent) {
return mService;
}
}
<service
android:name=".AIDLTestService"
android:enabled="true"
android:exported="true"
android:process=":remote" />
public class AIDLTestActivity extends AppCompatActivity implements ServiceConnection {
private static final String TAG = "AIDLTestActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aidl_test);
bindService(new Intent(this, AIDLTestService.class), this, BIND_AUTO_CREATE);
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IAIDLTest aidlTest = IAIDLTest.Stub.asInterface(service);
try {
for (Notification notification : aidlTest.getNotifications()) {
Log.d(TAG, "onServiceConnected: notification title = "
+ notification.extras.get(Notification.EXTRA_TITLE));
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
Boom!!!可以看到出现报错的情况了。下面来看一下该如何解决。
完整代码见:
https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/content/pm/ParceledListSlice.java
/**
* Transfer a large list of Parcelable objects across an IPC. Splits into
* multiple transactions if needed.
* <p>
* Caveat: for efficiency and security, all elements must be the same concrete type.
* In order to avoid writing the class name of each object, we must ensure that
* each object is the same type, or else unparceling then reparceling the data may yield
* a different result if the class name encoded in the Parcelable is a Base type.
*/
public class ParceledListSlice<T extends Parcelable> implements Parcelable {
private static final String TAG = "NotificationParceledListSlice";
private static final boolean DEBUG = false;
private static final int MAX_IPC_SIZE = IBinder.getSuggestedMaxIpcSizeBytes();
private final List<T> mList;
private int mInlineCountLimit = Integer.MAX_VALUE;
public ParceledListSlice(List<T> list) {
mList = list;
}
private ParceledListSlice(Parcel p, ClassLoader loader) {
final int N = p.readInt();
mList = new ArrayList<T>(N);
if (DEBUG) Log.d(TAG, "Retrieving " + N + " items");
if (N <= 0) {
return;
}
Creator<?> creator = readParcelableCreator(p, loader);
Class<?> listElementClass = null;
int i = 0;
while (i < N) {
if (p.readInt() == 0) {
break;
}
listElementClass = readVerifyAndAddElement(creator, p, loader, listElementClass);
if (DEBUG) Log.d(TAG, "Read inline #" + i + ": " + mList.get(mList.size() - 1));
i++;
}
if (i >= N) {
return;
}
final IBinder retriever = p.readStrongBinder();
while (i < N) {
if (DEBUG) Log.d(TAG, "Reading more @" + i + " of " + N + ": retriever=" + retriever);
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInt(i);
try {
retriever.transact(IBinder.FIRST_CALL_TRANSACTION, data, reply, 0);
} catch (RemoteException e) {
Log.w(TAG, "Failure retrieving array; only received " + i + " of " + N, e);
return;
}
while (i < N && reply.readInt() != 0) {
listElementClass = readVerifyAndAddElement(creator, reply, loader,
listElementClass);
if (DEBUG) Log.d(TAG, "Read extra #" + i + ": " + mList.get(mList.size() - 1));
i++;
}
reply.recycle();
data.recycle();
}
}
private Class<?> readVerifyAndAddElement(Creator<?> creator, Parcel p,
ClassLoader loader, Class<?> listElementClass) {
final T parcelable = readCreator(creator, p, loader);
if (listElementClass == null) {
listElementClass = parcelable.getClass();
} else {
verifySameType(listElementClass, parcelable.getClass());
}
mList.add(parcelable);
return listElementClass;
}
@SuppressWarnings("unchecked")
private T readCreator(Creator<?> creator, Parcel p, ClassLoader loader) {
if (creator instanceof ClassLoaderCreator<?>) {
ClassLoaderCreator<?> classLoaderCreator =
(ClassLoaderCreator<?>) creator;
return (T) classLoaderCreator.createFromParcel(p, loader);
}
return (T) creator.createFromParcel(p);
}
private static void verifySameType(final Class<?> expected, final Class<?> actual) {
if (!actual.equals(expected)) {
throw new IllegalArgumentException("Can't unparcel type "
+ actual.getName() + " in list of type "
+ (expected == null ? null : expected.getName()));
}
}
public List<T> getList() {
return mList;
}
/**
* Set a limit on the maximum number of entries in the array that will be included
* inline in the initial parcelling of this object.
*/
public void setInlineCountLimit(int maxCount) {
mInlineCountLimit = maxCount;
}
@Override
public int describeContents() {
int contents = 0;
final List<T> list = getList();
for (int i = 0; i < list.size(); i++) {
contents |= list.get(i).describeContents();
}
return contents;
}
/**
* Write this to another Parcel. Note that this discards the internal Parcel
* and should not be used anymore. This is so we can pass this to a Binder
* where we won't have a chance to call recycle on this.
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
final int N = mList.size();
final int callFlags = flags;
dest.writeInt(N);
if (DEBUG) Log.d(TAG, "Writing " + N + " items");
if (N > 0) {
final Class<?> listElementClass = mList.get(0).getClass();
writeParcelableCreator(mList.get(0), dest);
int i = 0;
while (i < N && i < mInlineCountLimit && dest.dataSize() < MAX_IPC_SIZE) {
dest.writeInt(1);
final T parcelable = mList.get(i);
verifySameType(listElementClass, parcelable.getClass());
writeElement(parcelable, dest, callFlags);
if (DEBUG) Log.d(TAG, "Wrote inline #" + i + ": " + mList.get(i));
i++;
}
if (i < N) {
dest.writeInt(0);
Binder retriever = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
if (code != FIRST_CALL_TRANSACTION) {
return super.onTransact(code, data, reply, flags);
}
int i = data.readInt();
if (DEBUG) Log.d(TAG, "Writing more @" + i + " of " + N);
while (i < N && reply.dataSize() < MAX_IPC_SIZE) {
reply.writeInt(1);
final T parcelable = mList.get(i);
verifySameType(listElementClass, parcelable.getClass());
writeElement(parcelable, reply, callFlags);
if (DEBUG) Log.d(TAG, "Wrote extra #" + i + ": " + mList.get(i));
i++;
}
if (i < N) {
if (DEBUG) Log.d(TAG, "Breaking @" + i + " of " + N);
reply.writeInt(0);
}
return true;
}
};
if (DEBUG) Log.d(TAG, "Breaking @" + i + " of " + N + ": retriever=" + retriever);
dest.writeStrongBinder(retriever);
}
}
}
protected void writeElement(T parcelable, Parcel reply, int callFlags) {
parcelable.writeToParcel(reply, callFlags);
}
protected void writeParcelableCreator(T parcelable, Parcel dest) {
dest.writeParcelableCreator(parcelable);
}
protected Creator<?> readParcelableCreator(Parcel from, ClassLoader loader) {
return from.readParcelableCreator(loader);
}
@SuppressWarnings("unchecked")
public static final ClassLoaderCreator<ParceledListSlice> CREATOR
= new ClassLoaderCreator<ParceledListSlice>() {
@Override
public ParceledListSlice createFromParcel(Parcel in) {
return new ParceledListSlice(in, getClass().getClassLoader());
}
@Override
public ParceledListSlice createFromParcel(Parcel in, ClassLoader loader) {
return new ParceledListSlice(in, loader);
}
@Override
public ParceledListSlice[] newArray(int size) {
return new ParceledListSlice[size];
}
};
}
package com.jimmysun.notificationdemo;
parcelable NotificationParceledListSlice<T>;
import android.app.Notification;
import com.jimmysun.notificationdemo.ParceledListSlice;
interface IAIDLTest {
ParceledListSlice<Notification> getNotifications();
}
private final IBinder mService = new IAIDLTest.Stub() {
@Override
public ParceledListSlice<Notification> getNotifications() {
List<Notification> notifications = new ArrayList<>();
for (int i = 0; i < 500; i++) {
notifications.add(new Notification.Builder(AIDLTestService.this,
"CHANNEL_ID")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(Icon.createWithResource(AIDLTestService.this,
R.drawable.ic_avatar))
.setContentTitle("标题文本" + i)
.setContentText("正文文本" + i)
.setContentIntent(NotificationUtils.createActivityPendingIntent(AIDLTestService.this, "AIDL 测试" + i))
.setAutoCancel(true)
.addAction(0, "按钮 1",
NotificationUtils.createActivityPendingIntent(AIDLTestService.this, "按钮 1" + i))
.addAction(0, "按钮 2",
NotificationUtils.createReceiverPendingIntent(AIDLTestService.this, "按钮 2" + i))
.build());
}
return new ParceledListSlice<>(notifications);
}
};
for (Notification notification : aidlTest.getNotifications().getList()) {
Log.d(TAG, "onServiceConnected: notification title = "
+ notification.extras.get(Notification.EXTRA_TITLE));
}
以上输出的结果验证了该方案没有问题~
@Override
public void writeToParcel(Parcel dest, int flags) {
final int N = mList.size();
final int callFlags = flags;
// 写入数据长度,为了读取时知道数据列表有多少数据
dest.writeInt(N);
if (DEBUG) Log.d(TAG, "Writing " + N + " items");
if (N > 0) {
final Class<?> listElementClass = mList.get(0).getClass();
// 写入类名,用于读取时获取 ClassLoaderCreator
writeParcelableCreator(mList.get(0), dest);
int i = 0;
// 循环写入数据,mInlineCountLimit 可以由调用方指定,默认为 MAX_VALUE;
// MAX_IPC_SIZE 为 binder 传输最大大小(64KB)
while (i < N && i < mInlineCountLimit && dest.dataSize() < MAX_IPC_SIZE) {
// 写入 1 代表一条数据
dest.writeInt(1);
final T parcelable = mList.get(i);
// 校验当前写入的对象是不是和第一个对象是同一个类,如果不是则抛异常,方法定义见后面
verifySameType(listElementClass, parcelable.getClass());
// 写入当前数据,方法定义见后面
writeElement(parcelable, dest, callFlags);
if (DEBUG) Log.d(TAG, "Wrote inline #" + i + ": " + mList.get(i));
i++;
}
if (i < N) {
// 如果走到这里,说明上面没写完,需要分片传输了,先写个 0 说明还要读取
dest.writeInt(0);
// 下面写入 binder,这里是核心了,在读取的时候通过拿到 binder,一次一次调用 transact()
// 方法,来回调这里的 onTransact() 方法,每次传输尽可能多的数据,以达到分片传输的目的
Binder retriever = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
// 如果 code 不为 FIRST_CALL_TRANSACTION 则执行默认操作
if (code != FIRST_CALL_TRANSACTION) {
return super.onTransact(code, data, reply, flags);
}
// data 是读取方发来的数据,先告诉我现在读取到列表的哪个位置了
int i = data.readInt();
if (DEBUG) Log.d(TAG, "Writing more @" + i + " of " + N);
// 循环给 reply 写入数据,直到超出或结束
while (i < N && reply.dataSize() < MAX_IPC_SIZE) {
// 写入 1 代表一条数据
reply.writeInt(1);
// 验证并写入数据
final T parcelable = mList.get(i);
verifySameType(listElementClass, parcelable.getClass());
writeElement(parcelable, reply, callFlags);
if (DEBUG) Log.d(TAG, "Wrote extra #" + i + ": " + mList.get(i));
i++;
}
if (i < N) {
// 走到这里写入 0 来代表还没有读完
if (DEBUG) Log.d(TAG, "Breaking @" + i + " of " + N);
reply.writeInt(0);
}
return true;
}
};
if (DEBUG) Log.d(TAG, "Breaking @" + i + " of " + N + ": retriever=" + retriever);
dest.writeStrongBinder(retriever);
}
}
}
private static void verifySameType(final Class<?> expected, final Class<?> actual) {
if (!actual.equals(expected)) {
throw new IllegalArgumentException("Can't unparcel type "
+ actual.getName() + " in list of type "
+ (expected == null ? null : expected.getName()));
}
}
protected void writeElement(T parcelable, Parcel reply, int callFlags) {
parcelable.writeToParcel(reply, callFlags);
}
private final List<T> mList;
private NotificationParceledListSlice(Parcel p, ClassLoader loader) {
// 读取数据长度
final int N = p.readInt();
// 创建数据列表
mList = new ArrayList<T>(N);
if (DEBUG) Log.d(TAG, "Retrieving " + N + " items");
if (N <= 0) {
return;
}
// 通过类名读取 creator
Creator<?> creator = readParcelableCreator(p, loader);
Class<?> listElementClass = null;
// 循环遍历读取数据
int i = 0;
while (i < N) {
// 这里每读取一条数据的时候 readInt() 都返回 1,如果返回 0 就要走后面的分片读取的逻辑了
if (p.readInt() == 0) {
break;
}
// 验证读取数据的类型,并加入数据列表中,方法定义见后面
listElementClass = readVerifyAndAddElement(creator, p, loader, listElementClass);
if (DEBUG) Log.d(TAG, "Read inline #" + i + ": " + mList.get(mList.size() - 1));
i++;
}
// 如果读取完了就直接 return 掉
if (i >= N) {
return;
}
// 读取 binder 来进行分片传输
final IBinder retriever = p.readStrongBinder();
while (i < N) {
if (DEBUG) Log.d(TAG, "Reading more @" + i + " of " + N + ": retriever=" + retriever);
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
// 写入当前数据列表已经读取的位置
data.writeInt(i);
try {
// 调用 transact 来回调发送方 onTransact() 方法,把数据写到 reply 里
retriever.transact(IBinder.FIRST_CALL_TRANSACTION, data, reply, 0);
} catch (RemoteException e) {
Log.w(TAG, "Failure retrieving array; only received " + i + " of " + N, e);
return;
}
// 循环遍历 reply 里的数据,验证并添加数据到列表中
while (i < N && reply.readInt() != 0) {
listElementClass = readVerifyAndAddElement(creator, reply, loader,
listElementClass);
if (DEBUG) Log.d(TAG, "Read extra #" + i + ": " + mList.get(mList.size() - 1));
i++;
}
reply.recycle();
data.recycle();
}
}
private Class<?> readVerifyAndAddElement(Creator<?> creator, Parcel p,
ClassLoader loader, Class<?> listElementClass) {
final T parcelable = readCreator(creator, p, loader);
if (listElementClass == null) {
listElementClass = parcelable.getClass();
} else {
verifySameType(listElementClass, parcelable.getClass());
}
mList.add(parcelable);
return listElementClass;
}
@SuppressWarnings("unchecked")
private T readCreator(Creator<?> creator, Parcel p, ClassLoader loader) {
if (creator instanceof ClassLoaderCreator<?>) {
ClassLoaderCreator<?> classLoaderCreator =
(ClassLoaderCreator<?>) creator;
return (T) classLoaderCreator.createFromParcel(p, loader);
}
return (T) creator.createFromParcel(p);
}
最后推荐一下我做的网站,玩Android: wanandroid.com ,包含详尽的知识体系、好用的工具,还有本公众号文章合集,欢迎体验和收藏!
推荐阅读:
扫一扫 关注我的公众号
如果你想要跟大家分享你的文章,欢迎投稿~
┏(^0^)┛明天见!