【问题标题】:Loading an Image using Picasso使用毕加索加载图像
【发布时间】:2016-09-02 15:22:49
【问题描述】:

我正在使用PicassoURL 加载Image,运行应用程序后,我看到“应用程序可能在其主线程上做了太多工作”。要设置Image,我正在写这样的东西:

Picasso.with(ScrollingActivity.this).load(photoUrl).networkPolicy(NetworkPolicy.OFFLINE).into(userProfileImageView, new Callback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError() {
                with(ScrollingActivity.this).load(photoUrl).into(userProfileImageView);
            }
        });

现在我正在考虑使用AsyncTaskImage 设置为ImageView,为此我将代码修改为:

但是现在我不知道在doInBackground方法和onPostExecute方法中写什么。

我像这样使用AsyncTask 方法:

class SetImageTask extends AsyncTask<Void, Void, Void>
        {

            @Override
            protected Void doInBackground(Void... voids) {

                Picasso.with(ScrollingActivity.this).load(photoUrl).networkPolicy(NetworkPolicy.OFFLINE).into(userProfileImageView, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError() {
                        with(ScrollingActivity.this).load(photoUrl).into(userProfileImageView);
                    }
                });


                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            }
        }

但问题是我在doInBackground 方法中将图像设置为ImageView。所以我认为这需要在 UI 线程中完成。你能告诉我如何使用AsyncTask设置Image

【问题讨论】:

  • 尝试常规方式。 Picasso.with(ScrollingActivity.this).load(photoUrl).into(userProfileImageView); 并且没有异步任务。
  • 常规方式可能会在主 UI 中造成繁重的工作,所以我认为这就是我得到“应用程序可能在 UI 线程上做太多工作”的原因。我什至有更多的图片要使用 Picasso 加载,所以这就是我使用 AsyncTask 的方式
  • 你为什么使用networkPolicy(NetworkPolicy.OFFLINE)?
  • 如果数据离线,则离线加载数据
  • 毕加索已经有自己的异步机制了,我认为问题是由其他因素引起的。

标签: java android multithreading android-asynctask


【解决方案1】:

您不需要使用AsyncTask 或后台线程来使用Piccaso 加载图像。毕加索已经优化。它有自己的异步调用。你遇到的问题

“应用程序可能在其主线程上做了太多工作”

不是因为毕加索。你可以参考this链接查看"Application may be doing too much work on its main thread"背后的原因

【讨论】:

    【解决方案2】:

    使用Target,那么您就不需要AsyncTask,因为它会在后台解码。

    private Target target = new Target() {
        @Override
          public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { 
             //do whatever you need in here      
          }
    
        @Override
          public void onBitmapFailed() {
          }
    }
    
    private void loadBitmap() {
       Picasso.with(this).load("url").into(target);
    }
    

    确保您将Target 绑定到一个视图,否则它可能会在进程完成之前被垃圾回收。

    【讨论】:

    • 你能告诉我这是如何工作的,以及这是如何从 UI 线程下载图像的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2016-12-12
    • 1970-01-01
    相关资源
    最近更新 更多