【问题标题】:Image in android home screen widget loaded through Picasso only updates sometimes通过毕加索加载的android主屏幕小部件中的图像有时只会更新
【发布时间】:2021-05-06 13:25:15
【问题描述】:

我正在开发一个 Android 主屏幕小部件,它从一组 url(从 firebase 数据库获得)中选择一个随机图像 url,并显示该图像。小部件每 30 分钟更新一次,因此应该每 30 分钟左右显示一个新图像。

我正在使用 Picasso 显示来自 url 的图像。

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

if (currentWidget.url.length() > 0) {
    final RoundCornersTransformation transformation = new RoundCornersTransformation(50, 0);
    Picasso.get().load(currentWidget.url).memoryPolicy(MemoryPolicy.NO_CACHE).transform(transformation).into(new Target()  {
        @Override
        public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
            Log.d("PICASSO", "Bitmap Loaded");
            views.setImageViewBitmap(R.id.appwidget_image, bitmap);
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
            Log.d("PICASSO", "Bitmap Failed");
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            Log.d("PICASSO", "Bitmap Prepared");
        }
    });
}

我已经测试了url,并且它会定期更新,并且代码中没有逻辑错误,因为有时会显示图像。但是,大多数情况下,即使 url 更新并且我在控制台中获得“Bitmap Loaded”,小部件中的图像也不会更新。

【问题讨论】:

    标签: android bitmap imageview android-widget picasso


    【解决方案1】:

    好的,经过 10 个小时的搜索,我找到了问题并解决了问题。

    基本上,毕加索持有对目标类的弱引用,它会得到“垃圾收集”。因此,图像永远不会加载 FIRST TIME。因为我每次都选择一个随机 URL,所以仅在某些时候选择了相同的 URL,这就解释了为什么它只显示图像有时,而不是在第一次失败后每次都显示。

    我通过找到删除目标类的方法来修复它。这是固定的代码:

    if (currentWidget.url.length() > 0) {
        final RoundCornersTransformation transformation = new RoundCornersTransformation(50, 0);
        Picasso.get().load(currentWidget.url).transform(transformation).into(views, R.id.appwidget_image, new int[] {appWidgetId});
    }
    

    有用的帖子:

    1. onBitmapLoaded of Target object not called on first load
    2. https://stackoverflow.com/a/28335661/12029824

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 2014-09-06
      • 2019-12-12
      • 2017-02-19
      相关资源
      最近更新 更多