簡體   English   中英

使用glide異步加載圖像時,okhttp3引發NetworkOnMainThreadException

[英]okhttp3 throws NetworkOnMainThreadException when loading images asynchronously with glide

我正在嘗試像這樣將圖像異步加載到Leanback的CardPresenter中。

public interface CustomImageModel {  
    String requestCustomUrl(int width, int height);
}

public static class CustomImageModelGrabber implements CustomImageModel {

    public CustomImageModelGrabber() {

    }

    @Override
    public String requestCustomUrl(int width, int height) {
        OkHttpClient client = new OkHttpClient;
        Request request = new Request.Builder().url(image_url).build();
        return client.newCall(request).execute().body().string();
    }
}

public static class CustomImageUrlLoader extends BaseGlideUrlLoader<CustomImageModel> {  
    public CustomImageUrlLoader(Context context) {
        super( context );
    }

    @Override
    protected String getUrl(CustomImageModel model, int width, int height) {
        return model.requestCustomUrl();
    }
}

在CardPresenter.java中

@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {

    CustomImageModel customImageRequest = new CustomImageModelGrabber();

    Glide  
            .with( context )
            .using( new CustomImageUrlLoader( context ) )
            .load( customImageRequest )
            .into( imageView1 );
}

不幸的是,這不能按預期工作。 只有很少的圖像可以正確地加載到卡演示器中,但是大多數圖像卻沒有,並且會引發以下錯誤:

android.os.NetworkOnMainThreadException
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)

工作和不工作完全是隨機的。

我還嘗試在MainActivity.java中設置嚴格模式。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

盡管此解決方案可以正確加載所有圖像,並且不會引發任何NetworkOnMainThreadException錯誤,但它會帶來巨大的性能問題。 滾動變得緩慢而緩慢,向我顯示以下消息:

I/Choreographer: Skipped 182 frames!  The application may be doing too much work on its main thread.

有什么解決方案可以使圖像異步加載,同時仍然保持平滑和良好的性能?

我的方法是完全錯誤的。 我以為BaseGlideUrlLoader在后台線程上運行,但事實並非如此。

因此,要執行的代碼如下:

@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {

    final ImageCardView cardView = (ImageCardView) viewHolder.view;

    OkHttpClient client = new OkHttpClient;
    Request request = new Request.Builder().url(image_url).build();


    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try (ResponseBody responseBody = response.body()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);


            String imageFromResponse = responseBody.string();
            // do whatever is needed to get the image (i.e JSON-handling)

            Handler mainHandler = new Handler(Looper.getMainLooper());
            Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    Glide.with(cardView.getContext())
                            .load(imagefromResponse)
                            .error(mDefaultCardImage)
                            .into(cardView.getMainImageView());
                }
            };
        }
    });


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM