我想使用AIDL将String和Bitmap传递给服务。该服务实现了这个AIDL方法:
void addButton(in Bundle data);
在我的例子中,Bundle包含一个String和一个Bitmap。
调用应用程序(客户端)具有以下代码:
...
// Add text to the bundle
Bundle data = new Bundle();
String text = "Some text";
data.putString("BundleText", text);
// Add bitmap to the bundle
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.myIcon);
data.putParcelable("BundleIcon", icon);
try {
myService.addButton(data);
} catch (RemoteException e) {
Log.e(TAG, "Exception: ", e);
e.printStackTrace();
}
...
在服务端,我有一个带有此代码的ButtonComponent类:
public final class ButtonComponent implements Parcelable {
private final Bundle mData;
private ComponComponent(Parcel source) {
mData = source.readBundle();
}
public String getText() {
return mData.getString("BundleText");
}
public Bitmap getIcon() {
Bitmap icon = (Bitmap) mData.getParcelable("BundleIcon");
return icon;
}
public void writeToParcel(Parcel aOutParcel, int aFlags) {
aOutParcel.writeBundle(mData);
}
public int describeContents() {
return 0;
}
}
创建ButtonComponent后,服务使用ButtonComponent对象中的文本和图标创建一个按钮:
...
mInflater.inflate(R.layout.my_button, aParent, true);
Button button = (Button) aParent.getChildAt(aParent.getChildCount() - 1);
// Set caption and icon
String caption = buttonComponent.getText();
if (caption != null) {
button.setText(caption);
}
Bitmap icon = buttonComponent.getIcon();
if (icon != null) {
BitmapDrawable iconDrawable = new BitmapDrawable(icon);
button.setCompoundDrawablesWithIntrinsicBounds(iconDrawable, null, null, null);
}
...
结果,按钮显示正确的文本,我可以看到图标的空间,但是没有绘制实际的位图(即文本左侧有一个空白区域)。
以这种方式将Bitmap放入Bundle是否正确?
如果我应该使用Parcel(vs Bundle)有没有办法在AIDL方法中维护单个'data'参数以保持文本和图标在一起?
附带问题:我如何决定使用Bundles vs Parcels?
非常感谢。
答案 0 :(得分:3)
以下是第二个问题的答案。
来源:http://www.anddev.org/general-f3/bundle-vs-parcel-vs-message-t517.html
Bundle在功能上等同于标准Map。我们的原因 不只是使用Map是因为在使用Bundle的上下文中, 唯一合法的东西就是基本的东西 字符串,整数等。因为标准Map API允许您插入 任意对象,这将允许开发人员将数据放入 映射系统实际上不能支持,这会导致奇怪, 非直观的应用程序错误。 Bundle是为了取代Map而创建的 使用类型安全容器,使其明确地清除它 支持原语。
Parcel类似于Bundle,但更复杂,可以 支持更复杂的类序列化。应用可以 实现Parcelable接口以定义特定于应用程序 可以传递的类,特别是在使用服务时。 Parcelables可能比Bundles更复杂,但是它来自于 成本显着提高了开销。
Bundle和Parcel都是数据序列化机制,并且用于 大部分都是在应用程序代码传递数据时使用的 流程。但是,因为Parcel的开销要高得多 Bundle,Bundles用于更常见的地方,如onCreate 方法,其中开销必须尽可能低。包裹最多 常用于允许应用程序使用逻辑定义服务 可以使用应用程序有意义的类作为方法参数的API 并返回值。如果我们在那里需要Bundle,那就会导致 非常笨重的API。您通常应该保留您的服务API 尽可能简单,因为原语将序列化更多 比定制的Parcelable类有效。
答案 1 :(得分:2)
解决。
问题是Android不支持我使用的PNG。 代码:
icon.getConfig()
返回null。
答案 2 :(得分:1)
虽然gt_ebuddy给出了一个很好的答案,但我对你的问题只有一点注意事项:
问题:您正在尝试将Bitmap
对象传递给内存,它可以很好;但是,传递这样的许多Bitmap
个对象绝对不是一件好事。真的很糟糕。
我的解决方案:该图片已存在于resources
中,它具有唯一的ID
;利用它。您可以使用Bitmaps
或ID
传递Bundle
,而不是尝试传递大量Parcel
,但Bundle
更适合简单的数据结构。