Search code examples
androidbitmapbundleparcelableparcel

Putting a Bitmap into a Bundle


I want to pass a String and a Bitmap to a Service using AIDL. The Service implements this AIDL method:

void addButton(in Bundle data);

In my case, the Bundle contains a String and a Bitmap.

The calling application (client) has this code:

...
// 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();
}
...

On the service end, I have a ButtonComponent class with this code:

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;
    }
}

After creating a ButtonComponent, the Service creates a button using the text and icon from the ButtonComponent object:

...
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 a result, the button is displayed with the correct text and I can see the space for the icon, but the actual bitmap is not drawn (i.e. there's an empty space on the left side of the text).

Is it correct to put a Bitmap into a Bundle in this way?

If I should use a Parcel (vs a Bundle) is there any way to maintain a single 'data' argument in the AIDL method to keep text and icon together?

Side question: How do I decide to use Bundles vs Parcels?

Many thanks.


Solution

  • Solved.

    Problem was that the PNG I was using is not supported by Android. The code:

    icon.getConfig()
    

    returns null.