Retrofit 和下载图像时出现 NetworkOnMain 错误

NetworkOnMain error with Retrofit and downloading an image

我在下载用户图像时遇到 NetworkOnMainThread 错误。 它在以下行崩溃: byte[] imgBytes = body.bytes(); 这是在 RetroFit 中的 onResponse 方法中。我的理解是这个方法不在主线程上。还是与 UI 话题不同?

这是我的代码。

private void syncPersonPhoto(final DBHelper db, final ArrayList<Person> syncPersons, final int current) {
        final Person person = syncPersons.get(current);
        Call<ResponseBody> photoSyncCall = RestClient.get(context).getPersonPhoto(person.getPersonCode(), person.getPersonTypeCode());
        photoSyncCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    ResponseBody body = response.body();
                    try {
                        byte[] imgBytes = body.bytes(); <--- ERROR HERE
                        body.close();
                        String imgBase64 = Base64.encodeToString(imgBytes, Base64.NO_WRAP);
                        db.addPersonImage(person.getPersonCode(), person.getPersonType(), imgBase64);
                    } catch (IOException e) {
                        log.log(TAG, "Bytes array couldn't be populated: " + e);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

有人能看出问题吗?

谢谢。

请求本身是在后台线程中执行的,是的。但是响应回调 onResponseonFailure 被分派到主线程并在主线程上执行。

您在其中所做的任何工作都可能与网络无关,否则您将看到您遇到的错误。

ResponseBodyJavaDoc说:

A one-shot stream from the origin server to the client application with the raw bytes of the response body. Each response body is supported by an active connection to the webserver. This imposes both obligations and limits on the client application.

你看,你对 bytes() 的调用正在使用仍然打开的网络服务器连接。此调用在 onResponse 回调内执行,因此在主线程内执行,这会导致 NetworkOnMainThreadException.