Search code examples
androidandroid-widgetandroid-glideremoteviewandroid-remoteview

Load ImageView from URL into RemoteView of a Home Screen Widget


I'm developing a simple Widget to my Android app based on the Google StackWidget sample: https://android.googlesource.com/platform/development/+/master/samples/StackWidget/src/com/example/android/stackwidget/StackWidgetService.java

I'm using the Glide image library and trying to populate an ImageView on getViewAt method of StackWidgetService class that extends RemoteViewsService. My code is similar to:

Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(() ->
    Glide.with(context)
        .asBitmap()
        .load(widgetItems.get(position).image_url)
        .into(new SimpleTarget<Bitmap>(512, 512) {
            @Override
            public void onResourceReady(Bitmap bitmap, Transition transition) {
                rv.setImageViewBitmap(R.id.widget_item_image, bitmap);
            }
        })
);

What's the best way of loading images from an URL to populate a RemoteView from an Android Widget?


Solution

  • Just need to do it synchronously. This seems to work fine:

        try {
            Bitmap bitmap = Glide.with(context)
                    .asBitmap()
                    .load(widgetItems.get(position).image_url)
                    .submit(512, 512)
                    .get();
    
            rv.setImageViewBitmap(R.id.widget_item_image, bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }