android - 如何修复尝试通过改造抛出 OutOfMemoryError 时抛出的 OutOfMemoryError

标签 android out-of-memory retrofit

我在我的应用程序中使用改造来下载一些媒体文件,如视频、mp3、jpg、pdf 等。当我想下载一个 55MB 的 mp4 格式的大文件时,这是一个问题。当我想下载这个文件时,我收到这样的错误:

OutOfMemoryError threw while trying to throw OutOfMemoryError; no stack trace available

这是我的代码:

  private void downloadFile() {

    ArrayList<FileModel> filesInDB = G.bootFileFromFileDB();

    for (final FileModel fm : filesInDB) {

      APIService downloadService = ServiceGenerator.createServiceFile(APIService.class, "username", "password");

      //Id of apk file that you want to download
      Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync("file/download/" + String.valueOf(fm.getFileId()));
      call.enqueue(new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
          if (response.isSuccess()) {

            Log.d("LOGOO", "server contacted and has file");

            boolean writtenToDisk = writeResponseBodyToDisk(response.body(), fm.getFileName(), fm.getFileExtension());

            response = null;


            Log.d("LOGOO", "file download was a success? " + writtenToDisk);


          } else {
            Log.d("LOGOO", "server contact failed");
          }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
          Log.i("LOGO", "Error is : " + t.getMessage());

          Toast.makeText(ActivityInternet.this, R.string.internet_error, Toast.LENGTH_LONG).show();
          Intent intent = new Intent(ActivityInternet.this, ActivityStartup.class);
          startActivity(intent);
        }
      });
    }

这是我正在使用的“writeResponseBodyToDisk”方法:

  private boolean writeResponseBodyToDisk(ResponseBody body, String fileName, String fileExtension) {

    try {

      // Location to save downloaded file and filename
      File futureStudioIconFile = new File(G.DIR_APP + fileName + fileExtension);
      InputStream inputStream = null;
      OutputStream outputStream = null;
      try {
        byte[] fileReader = new byte[4096];
        long fileSize = body.contentLength();
        long fileSizeDownloaded = 0;
        inputStream = body.byteStream();
        outputStream = new FileOutputStream(futureStudioIconFile);
        while (true) {
          int read = inputStream.read(fileReader);
          if (read == -1) {
            break;
          }
          outputStream.write(fileReader, 0, read);
          fileSizeDownloaded += read;
          Log.d("LOGO", "file download: " + fileSizeDownloaded + " of " + fileSize);
        }
        outputStream.flush();
        return true;
      } catch (IOException e) {
        return false;
      } finally {
        if (inputStream != null) {
          inputStream.close();
        }
        if (outputStream != null) {
          outputStream.close();
        }
      }
    } catch (IOException e) {
      return false;
    }


  }

最后这是我的 createServiceFile 方法:

public static <S> S createServiceFile(Class<S> serviceClass, String username, String password) {
        if (username != null && password != null) {

            String credentials = username + ":" + password;
            final String basic =
              "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request original = chain.request();
                    Request.Builder requestBuilder = original.newBuilder()
                      .header("Authorization", basic)
                      .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,audio/mp4,image/jpeg,*/*;q=0.8")
                      .method(original.method(), original.body());
                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });
        }
        OkHttpClient client = httpClient.build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);
    }

如果你能帮助我,我将不胜感激:)

最佳答案

retrofit处理大文件下载有4点需要注意:

  1. 确保您使用的是 android:largeHeap="true"在你的AndroidManifest.xml ,作为 <application> 的属性.
  2. 确保您使用的是 @Streaming来自 Retrofit 的注释,以便流式传输解决方案而不是将其作为一个整体读取,这会占用内存。
  3. 使用 AsyncTask 处理响应如 this link 中所述.在您的情况下,这意味着调用 writeResponseBodyToDisk来自 AsyncTask .
  4. 最后要避免的是使用 Level.BODY okhttp3日志拦截器。将它与流式响应一起使用仍然会将整个响应主体保留在内存中,从而抵消了 @Streaming 的优势。改造提供的支持。

关于android - 如何修复尝试通过改造抛出 OutOfMemoryError 时抛出的 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44219530/

相关文章:

android - Android Retrofi 中 SingleObserver onSubscribe 函数总是返回 null

android - 为什么有人会在 Retrofit 中使用execute()函数

android - Retrofit 2 接口(interface) - 正确的方法?

android - Android 上的傅里叶变换

Android MediaPlayer 停止()不起作用

android - 为什么我在简单地执行 setContentView(R.layout.somelayout) 时会出现内存泄漏?

java - 我应该捕获 OutOfMemoryError 吗?

android - Activity.setResult(int) 和 Activity 生命周期

java - 安卓 SQLite : Is there a way to encrypt the entire data-base?

Java : How to find string patterns in a LARGE binary file?