feat: implement custom Coil image loader with retry interceptor and enhance UI with robust image loading states

This commit is contained in:
Jhony Cesar
2026-08-06 08:07:07 -04:00
parent 554a34f8b1
commit ec48078f1a
4 changed files with 191 additions and 10 deletions

View File

@@ -0,0 +1,112 @@
package com.example
import android.app.Application
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.disk.DiskCache
import coil.memory.MemoryCache
import coil.request.CachePolicy
import com.example.util.AppLogger
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.io.IOException
import java.util.Random
class MainApplication : Application(), ImageLoaderFactory {
override fun onCreate() {
super.onCreate()
}
override fun newImageLoader(): ImageLoader {
val okHttpClient = OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.addInterceptor(RetryInterceptor(applicationContext, maxRetries = 3))
.build()
return ImageLoader.Builder(this)
.okHttpClient(okHttpClient)
.memoryCache {
MemoryCache.Builder(this)
.maxSizePercent(0.25) // 25% da memória RAM disponível
.build()
}
.diskCache {
DiskCache.Builder()
.directory(cacheDir.resolve("image_cache"))
.maxSizeBytes(50 * 1024 * 1024) // 50 MB de cache em disco (~100 fotos de 500KB)
.build()
}
.diskCachePolicy(CachePolicy.ENABLED)
.memoryCachePolicy(CachePolicy.ENABLED)
.networkCachePolicy(CachePolicy.ENABLED)
.crossfade(true)
.build()
}
}
class RetryInterceptor(
private val context: android.content.Context,
private val maxRetries: Int = 3
) : Interceptor {
private val random = Random()
private val appLogger by lazy { AppLogger.getInstance(context) }
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val urlStr = request.url.toString()
var response: Response? = null
var lastException: Exception? = null
for (attempt in 1..maxRetries) {
try {
response?.close()
response = chain.proceed(request)
if (response.isSuccessful) {
return response
} else if (response.code in 500..599 && attempt < maxRetries) {
response.close()
val delayMs = 300L + random.nextInt(700) // Intervalo aleatório de 300ms a 1000ms
appLogger.logWarning(
"ImageDownload",
"Tentativa $attempt de $maxRetries falhou para $urlStr (HTTP ${response.code}). Aguardando ${delayMs}ms para tentar novamente..."
)
Thread.sleep(delayMs)
} else {
if (!response.isSuccessful) {
appLogger.logWarning(
"ImageDownload",
"Download de imagem retornou HTTP ${response.code} para $urlStr após $attempt tentativa(s)."
)
}
return response
}
} catch (e: IOException) {
lastException = e
if (attempt < maxRetries) {
val delayMs = 300L + random.nextInt(700)
appLogger.logWarning(
"ImageDownload",
"Falha de rede na tentativa $attempt de $maxRetries para $urlStr: ${e.message}. Tentando em ${delayMs}ms..."
)
try {
Thread.sleep(delayMs)
} catch (ie: InterruptedException) {
Thread.currentThread().interrupt()
throw e
}
}
}
}
if (response != null) {
return response
}
val errorMsg = "Falha no download da foto após $maxRetries tentativas: ${lastException?.message ?: "Erro de rede"}. URL: $urlStr"
appLogger.logError("ImageDownload", errorMsg, lastException)
throw lastException ?: IOException(errorMsg)
}
}