Search code examples
androidbitmapuniversal-image-loader

Android Universal Image Loader to get bitmaps from Another app's Resources


I know it is possible to use another app's bitmaps using the following blockquote, or similar:

String packageName = "com.some.package";

Resources res = getPackageManager().getResourcesForApplication(packageName);

int resId = res.getIdentifier("some_bitmap_icon", "drawable", packageName);

((BitmapDrawable) res.getDrawable(resId)).getBitmap();

Is there anyway of passing res and resIdto Android-Universal-Image-Loader to directly load the bitmap from the 3rd party app?

Or would I have to copy the bitmap to the SD card, then display it by passing "file:///mnt/sdcard/some_temp_bitmap"


Solution

  • Thanks to @CommonsWare for pointing me in the right direction.

    I started by extending BaseImageDownloader, and overriding getStreamFromOtherSource:

    public class CustomImageDownloader extends BaseImageDownloader {
        public CustomImageDownloader(Context context) {
            super(context);
        }
    
        @Override
        protected InputStream getStreamFromOtherSource(String imageUri, Object extra) {
            if (imageUri.startsWith("thirdparty://")) {
                try {
                    String drawableString = imageUri.replace("thirdparty://", "");
                    String[] location = drawableString.split("/");
    
                    Resources res = context.getPackageManager().getResourcesForApplication(location[0]);
                    return res.openRawResource(Integer.parseInt(location[1]));
                } catch (PackageManager.NameNotFoundException e) {
                    return null;
                }
            } else throw new UnsupportedOperationException(imageUri);
        }
    }
    

    Then implemented this class in my ImageLoaderConfiguration using:

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        .imageDownloader(new CustomImageDownloader(context))
        .build();
    ImageLoader.getInstance().init(config);
    

    Then it's just a case of starting the image loader using:

    ImageLoader.getInstance().displayImage("thirdparty://"+ packageName + "/" + resId, imageView, options);
    

    Now Android universal image loader can be used for loading bitmaps from 3rd party apps.