我想使用AIDL將一個字符串和一個位圖傳遞給一個服務。該服務實現此AIDL方法:將一個位圖放入一個包中
void addButton(in Bundle data);
在我的情況下,該Bundle包含一個字符串和一個位圖。
調用應用程序(客戶端)有這樣的代碼:
...
// 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);
}
...
As結果是,按鈕顯示正確的文本,我可以看到該圖標的空間,但實際的位圖沒有繪製(即,文本左側有一個空白空間)。
以這種方式將一個位圖放入一個包中是否正確?
如果我應該使用Parcel(vs a Bundle),有沒有辦法在AIDL方法中保留單個'data'參數來保持文本和圖標在一起?
旁邊的問題:我如何決定使用Bundles vs Parcels?
非常感謝。
謝謝。在我的場景中,位圖大約是900字節,這可能是相當大的,我想避免將它們全部包含在服務的APK中(可能有很多不同的客戶端)。如果我使用了唯一的ID,我猜客戶和服務的包都會包含實際的PNG ...對嗎? – rippeltippel
所有的圖像應該包含在'/ res/drawable'目錄中 –