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

@@ -6,6 +6,7 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"

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)
}
}

View File

@@ -1115,6 +1115,18 @@ fun OSListItemCard(
}
}
fun resolvePhotoModel(path: String): String {
val trimmed = path.trim()
if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("/")) {
return trimmed
}
if (trimmed.startsWith("photos/")) {
val encoded = android.net.Uri.encode(trimmed)
return "https://firebasestorage.googleapis.com/v0/b/cargill-parada-os.appspot.com/o/$encoded?alt=media"
}
return trimmed
}
@Composable
fun FullscreenPhotoViewerDialog(
photoPath: String,
@@ -1215,14 +1227,41 @@ fun FullscreenPhotoViewerDialog(
}
// Image display
coil.compose.AsyncImage(
model = photoPath,
val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath) }
var retryKey by remember { mutableStateOf(0) }
coil.compose.SubcomposeAsyncImage(
model = coil.request.ImageRequest.Builder(context)
.data(resolvedModel)
.setParameter("retry_key", retryKey)
.crossfade(true)
.diskCachePolicy(coil.request.CachePolicy.ENABLED)
.memoryCachePolicy(coil.request.CachePolicy.ENABLED)
.build(),
contentDescription = "Visualização em Tela Cheia",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.82f)
.padding(16.dp),
contentScale = androidx.compose.ui.layout.ContentScale.Fit
contentScale = androidx.compose.ui.layout.ContentScale.Fit,
loading = {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator(color = Color.White, modifier = Modifier.size(36.dp), strokeWidth = 3.dp)
}
},
error = {
Box(
modifier = Modifier
.fillMaxSize()
.clickable { retryKey++ },
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(Icons.Default.Refresh, contentDescription = "Recarregar", tint = Color.White, modifier = Modifier.size(32.dp))
Spacer(modifier = Modifier.height(8.dp))
Text("Falha ao carregar imagem. Toque para tentar novamente.", color = Color.White, fontSize = 12.sp)
}
}
}
)
}
}
@@ -1838,11 +1877,35 @@ fun EditActivityBottomSheet(
border = BorderStroke(2.dp, if (isNew) BrandGreen else Color(0xFFE0E0E0))
) {
Box(modifier = Modifier.fillMaxSize()) {
coil.compose.AsyncImage(
model = photoPath,
val resolvedModel = remember(photoPath) { resolvePhotoModel(photoPath) }
var retryKey by remember { mutableStateOf(0) }
coil.compose.SubcomposeAsyncImage(
model = coil.request.ImageRequest.Builder(LocalContext.current)
.data(resolvedModel)
.setParameter("retry_key", retryKey)
.crossfade(true)
.diskCachePolicy(coil.request.CachePolicy.ENABLED)
.memoryCachePolicy(coil.request.CachePolicy.ENABLED)
.build(),
contentDescription = "Miniatura da foto",
modifier = Modifier.fillMaxSize(),
contentScale = androidx.compose.ui.layout.ContentScale.Crop
contentScale = androidx.compose.ui.layout.ContentScale.Crop,
loading = {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator(color = BrandGreen, modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
}
},
error = {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(0xFFF5F5F5))
.clickable { retryKey++ },
contentAlignment = Alignment.Center
) {
Icon(Icons.Default.Refresh, contentDescription = "Recarregar", tint = Color.Gray, modifier = Modifier.size(16.dp))
}
}
)
if (isNew) {
// Badge NOVA