3

В ходе разработки использую Retrofit2.
В Retrofit2 использую logger:

.client(new OkHttpClient.Builder().addInterceptor(new HttpLoggingInterceptor().setLevel(BODY)).build())// Logging

Как мне сделать чтобы в релизной версии не было этой зависимости?

Если в Gradle я укажу Logger'у testImplementation тогда мне придется закомментировать строку Logger'а.

2 ответа 2

4

Например, так:

В build.gradle описать зависимость, как

debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'

Создать файл src/debug/java/com/example/logging/LoggingInterceptor:

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

import static okhttp3.logging.HttpLoggingInterceptor.Level.BODY;

public class LoggingInterceptor implements Interceptor {

    private final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor().setLevel(BODY);

    @Override
    public Response intercept(Chain chain) throws IOException {
        return interceptor.intercept(chain);
    }
}

Создать файл src/release/java/com/example/logging/LoggingInterceptor:

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

public class LoggingInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        return chain.proceed(chain.request());
    }
}

И использовать этот интерсептор в проекте:

.client(new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build())// Logging

Тогда, при сборке assembleDebug будет использоваться интерсептор с логгером, а при сборке assembleRelease будет использоваться пустой интерсептор, а библиотека с логгером не попадет в classpath.

0

Есть менее мудреный способ:

public class LoggingInterceptor implements Interceptor {

    private final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor().setLevel(BODY);

    @Override
    public Response intercept(Chain chain) throws IOException {
        if(BuildConfig.DEBUG)
           return interceptor.intercept(chain); //в дебажной версии сработает эта ветка
        else
           return chain.proceed(chain.request()); //в релизной эта ветка
    }
} 

Ключ переменная BuildConfig.DEBUG, которая в релизе false

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.