java - 致命异常 : java. lang.OutOfMemoryError 使用 okhttp3 okio 下载文件

标签 java android okhttp okio

我有一个应用程序可以从网络上下载内容。 音乐、视频、pdf……就像一个下载管理器。

但现在每次下载内容时都会崩溃:

E/LVN/advanced_memory_manager.c: ---------------------------------- AMM report ------------------------------
-> Memory Currently Allocated: 0 bytes <=> 0 components
-> Max Memory Need: 512000 bytes
-> Overall Memory Allocation: 515652 bytes (l:423)
E/art: Throwing OutOfMemoryError "Failed to allocate a 2060 byte allocation with 16777232 free bytes and 308MB until OOM; failed due to fragmentation (required continguous free 4096 bytes where largest contiguous free 0 bytes)"
E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: com.rokki.life2, PID: 32171
    java.lang.OutOfMemoryError: Failed to allocate a 2060 byte allocation with 16777232 free bytes and 308MB until OOM; failed due to fragmentation (required continguous free 4096 bytes where largest contiguous free 0 bytes)
        at okio.Segment.<init>(Segment.java:58)
        at okio.SegmentPool.take(SegmentPool.java:46)
        at okio.Buffer.writableSegment(Buffer.java:1114)
        at okio.Okio$2.read(Okio.java:137)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
        at okio.RealBufferedSource.read(RealBufferedSource.java:50)
        at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:381)
        at okio.RealBufferedSource.request(RealBufferedSource.java:71)
        at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:225)
        at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:187)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
        at okhttp3.RealCall.access$100(RealCall.java:30)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 106405148 byte allocation with 16777120 free bytes and 82MB until OOM
       at java.lang.String.<init>(String.java:332)
       at java.lang.String.<init>(String.java:371)
       at okio.Buffer.readString(Buffer.java:579)
       at okio.Buffer.readString(Buffer.java:562)
       at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:244)
       at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:187)
       at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
       at okhttp3.RealCall.access$100(RealCall.java:30)
       at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
       at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)

我已经将它添加到我的 list 中:

<application
    android:name=".app.MyApp"
    android:allowBackup="true"
    android:hardwareAccelerated="true"
    android:icon="@mipmap/ic_launcher"
    tools:replace="android:icon"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.NoActionBar">

代码示例:

private OkHttpClient client;


onViewCreated...{

    //Initiate OkHttp with interceptor
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    client = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .build();

...
}



private void downloadPdf() {
AsyncTask.execute(new Runnable() {
    @Override
    public void run() {


    client
        .newCall(getRequest(Config._API_PDF))
        .enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ...
            }


              @Override
                public void onResponse(Call call, Response response) throws IOException {


              try {

                                    InputStream ins = response.body().byteStream();
                                    BufferedReader in = new BufferedReader(new InputStreamReader(ins));

                                    String lineTotal = "";
                                    while (true) {
                                        String line = in.readLine();
                                        if (line == null)
                                            break;
                                        else
                                            lineTotal += line;
                                    }

                                    ...json parsing ...



...

我的 BuildGradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.my.app"
        minSdkVersion 17
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

        ndk { abiFilters "armeabi", "x86", "mips" }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    final SUPPORT_LIBRARY_VERSION = '23.2.0'
    final PLAY_SERVICES_VERSION = '8.3.0'
    final RETROFIT_VERSION = '2.0.0'
    final OKHTTP3_VERSION = '3.2.0'


    compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:cardview-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"


    compile "com.squareup.retrofit2:retrofit:$RETROFIT_VERSION"
    compile "com.squareup.retrofit2:converter-gson:$RETROFIT_VERSION"
    compile "com.squareup.retrofit2:adapter-rxjava:$RETROFIT_VERSION"
    compile "com.squareup.okhttp3:logging-interceptor:$OKHTTP3_VERSION"
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.jakewharton:butterknife:7.0.1'

}

然后我有另一种类似的方法来下载视频...

有没有人以前遇到过这个? 谢谢

最佳答案

当您使用 HttpLoggingInterceptor.Level.BODY 时,您尝试下载大文件,会将所有主体保存在内存中以供日志使用。

这很容易导致 OOM。

尝试删除日志正文或只记录 NONE 、基本或标题,然后重试。

当您尝试获取大文件时,可以像这样在 retrofit2 中使用 @Streaming。

@Streaming
@GET
fun downloadFileWithDynamicUrlSync(@Url fileUrl: String): Call<ResponseBody>

尝试在此处删除日志主体。

onViewCreated...{

//Initiate OkHttp with interceptor
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);

试试这个。

onViewCreated...{

//Initiate OkHttp with interceptor
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.NONE);

关于java - 致命异常 : java. lang.OutOfMemoryError 使用 okhttp3 okio 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36643280/

相关文章:

java - 得到 'IOException: hostname was not verified' ,尽管给定的主机名(IP 地址)与通用名称匹配

java - 动画时 JPanel 与 JFrame

android - Beagleboard 上的爪子服务器

android - 如何在 Android 中使用 okhttp 暂停/恢复下载

java - 面向对象的项目类结构

android - 在整个存储中搜索媒体文件或文件类型 - android

java - Android改造url开头的查询

java - 角色出现

java - 如何访问JPanel?

java - dependencyManagement 的传递效应