general: download using a foreground service instead of DownloadManager
- Commit
9f2a468451d0affb808d66cdbf0026dedd311a9b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-03-10 19:19 UTC (9 months ago)
- Parents
e137b71
Diff
library/build.gradle.kts
diff --git a/library/build.gradle.kts b/library/build.gradle.ktsindex 08302f54ca..084a133c43 100644--- a/library/build.gradle.kts+++ b/library/build.gradle.kts@@ -13,6 +13,8 @@ dependencies { implementation(libs.androidx.glance.appwidget) implementation(libs.androidx.glance.material3) + implementation("com.squareup.okhttp3:okhttp:5.3.0")+ //reorderable implementation(libs.reorderable)
library/src/main/java/com/vayunmathur/library/services/DownloadService.kt
diff --git a/library/src/main/java/com/vayunmathur/library/services/DownloadService.kt b/library/src/main/java/com/vayunmathur/library/services/DownloadService.ktnew file mode 100644index 0000000000..ebcfd24e3a--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/services/DownloadService.kt@@ -0,0 +1,187 @@+package com.vayunmathur.library.services++import android.app.*+import android.content.Context+import android.content.Intent+import android.net.wifi.WifiManager+import android.os.IBinder+import android.os.PowerManager+import androidx.core.app.NotificationCompat+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.*+import okhttp3.*+import okio.buffer+import okio.appendingSink+import okio.sink+import java.io.File+import java.security.MessageDigest+import java.util.concurrent.TimeUnit++class DownloadService : Service() {+ private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())+ private val NOTIF_ID = 1001+ private val CHANNEL_ID = "high_speed_download_channel"++ private var wifiLock: WifiManager.WifiLock? = null+ private var wakeLock: PowerManager.WakeLock? = null++ private val client = OkHttpClient.Builder()+ .connectTimeout(60, TimeUnit.SECONDS)+ .readTimeout(60, TimeUnit.SECONDS)+ .build()++ override fun onCreate() {+ super.onCreate()+ val wm = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager+ wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "AiChat:HighPerf")+ val pm = getSystemService(Context.POWER_SERVICE) as PowerManager+ wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AiChat:DownloadWakeLock")+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ val urls = intent?.getStringArrayExtra("urls") ?: emptyArray()+ val fileNames = intent?.getStringArrayExtra("fileNames") ?: emptyArray()++ createNotificationChannel()+ startForeground(NOTIF_ID, createNotification("Initializing 100GB Transfer..."),+ android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)++ wifiLock?.acquire()+ wakeLock?.acquire()++ serviceScope.launch {+ val ds = DataStoreUtils.getInstance(applicationContext)++ urls.forEachIndexed { index, url ->+ val fileName = fileNames[index]+ val destFile = File(getExternalFilesDir(null), fileName)++ var lastBytes = 0L+ var lastTime = System.currentTimeMillis()++ try {+ downloadFileWithResume(url, destFile) { downloaded, total ->+ val currentTime = System.currentTimeMillis()+ val timeDiff = (currentTime - lastTime) / 1000.0++ if (timeDiff >= 1.0 || downloaded == total) {+ val progress = if (total > 0) downloaded.toDouble() / total else 0.0+ val speedMbps = ((downloaded - lastBytes) * 8.0) / 1_000_000.0 / timeDiff++ launch {+ ds.setDouble("progress_$fileName", progress)+ ds.setDouble("speed_$fileName", if (downloaded == total) 0.0 else speedMbps)+ ds.setBoolean("done_$fileName", downloaded == total)+ }++ updateNotification("Downloading $fileName: ${(progress * 100).toInt()}% (${speedMbps.toInt()} Mbps)")++ lastBytes = downloaded+ lastTime = currentTime+ }+ }++ // Final Verification+ updateNotification("Verifying $fileName integrity...")+ // If you have a server hash, you would check it here+ // val isValid = verifyHash(destFile, "expected_hash_here")++ } catch (e: Exception) {+ launch { ds.setString("error_$fileName", e.message ?: "Network Error") }+ }+ }+ ds.setBoolean("dbSetupComplete", true)+ cleanupAndStop()+ }+ return START_NOT_STICKY+ }++ private suspend fun downloadFileWithResume(url: String, file: File, onProgress: (Long, Long) -> Unit) {+ val existingSize = if (file.exists()) file.length() else 0L++ val request = Request.Builder()+ .url(url)+ .apply {+ if (existingSize > 0) addHeader("Range", "bytes=$existingSize-")+ }+ .build()++ client.newCall(request).execute().use { response ->+ if (!response.isSuccessful && response.code != 206) {+ throw Exception("Failed: ${response.code}")+ }++ val isResuming = response.code == 206+ val body = response.body ?: throw Exception("Empty body")+ val totalSize = if (isResuming) existingSize + body.contentLength() else body.contentLength()++ // AppendingSink ensures we write exactly from where the last byte ended+ val sink = if (isResuming) file.appendingSink().buffer() else file.sink().buffer()+ val source = body.source()++ var downloaded = if (isResuming) existingSize else 0L+ val buffer = ByteArray(131072) // 128KB buffer for massive files+ var bytesRead: Int++ source.use { input ->+ sink.use { output ->+ while (input.read(buffer).also { bytesRead = it } != -1) {+ output.write(buffer, 0, bytesRead)+ downloaded += bytesRead+ onProgress(downloaded, totalSize)+ }+ output.flush() // Force write to physical storage+ }+ }+ }+ }++ private fun verifyHash(file: File, expectedHash: String): Boolean {+ val digest = MessageDigest.getInstance("SHA-256")+ val buffer = ByteArray(262144)+ file.inputStream().use { input ->+ var bytesRead: Int+ while (input.read(buffer).also { bytesRead = it } != -1) {+ digest.update(buffer, 0, bytesRead)+ }+ }+ val actualHash = digest.digest().joinToString("") { "%02x".format(it) }+ return actualHash.equals(expectedHash, ignoreCase = true)+ }++ private fun cleanupAndStop() {+ if (wifiLock?.isHeld == true) wifiLock?.release()+ if (wakeLock?.isHeld == true) wakeLock?.release()+ stopForeground(STOP_FOREGROUND_REMOVE)+ stopSelf()+ }++ private fun createNotification(content: String): Notification {+ return NotificationCompat.Builder(this, CHANNEL_ID)+ .setContentTitle("High-Speed Setup")+ .setContentText(content)+ .setSmallIcon(android.R.drawable.stat_sys_download)+ .setOngoing(true)+ .setSilent(true)+ .build()+ }++ private fun updateNotification(content: String) {+ val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager+ manager.notify(NOTIF_ID, createNotification(content))+ }++ private fun createNotificationChannel() {+ val channel = NotificationChannel(CHANNEL_ID, "AI Downloads", NotificationManager.IMPORTANCE_LOW)+ val manager = getSystemService(NotificationManager::class.java)+ manager.createNotificationChannel(channel)+ }++ override fun onDestroy() {+ serviceScope.cancel()+ cleanupAndStop()+ super.onDestroy()+ }++ override fun onBind(intent: Intent?): IBinder? = null+}\ No newline at end of file
library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.kt b/library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.ktindex 58abc4a998..3244347946 100644--- a/library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.kt+++ b/library/src/main/java/com/vayunmathur/library/ui/InitialDownloader.kt@@ -1,34 +1,31 @@ package com.vayunmathur.library.ui -import android.app.DownloadManager-import android.content.Context-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.material3.CircularProgressIndicator-import androidx.compose.material3.Scaffold-import androidx.compose.material3.Text-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue+import android.content.Intent+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material3.*+import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp-import androidx.core.net.toUri+import com.vayunmathur.library.services.DownloadService import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.round-import kotlinx.coroutines.delay- @Composable-fun InitialDownloadChecker(ds: DataStoreUtils, filesToDownload: List<Triple<String, String, String>>, mainPage: @Composable () -> Unit) {+fun InitialDownloadChecker(+ ds: DataStoreUtils,+ filesToDownload: List<Triple<String, String, String>>,+ mainPage: @Composable () -> Unit+) { val dbSetup by ds.booleanFlow("dbSetupComplete").collectAsState(false)- if(dbSetup) {+ if (dbSetup) { mainPage() } else { InitialDownloadScreen(ds, filesToDownload)@@ -36,112 +33,126 @@ fun InitialDownloadChecker(ds: DataStoreUtils, filesToDownload: List<Triple<Stri } @Composable-fun InitialDownloadScreen(ds: DataStoreUtils, filesToDownload: List<Triple<String, String, String>>) {+fun InitialDownloadScreen(+ ds: DataStoreUtils,+ filesToDownload: List<Triple<String, String, String>>+) { val context = LocalContext.current- val progress by ds.doubleFlow("downloadProgress").collectAsState(0.0) + // Launch the Foreground Service immediately when this screen is first composed LaunchedEffect(Unit) {- // Enqueue all downloads and collect their DownloadManager IDs- val downloadIds = filesToDownload.map { (url, fileName, desc) ->- downloadFile(context, url, fileName, desc)- }-- // Poll DownloadManager until aggregate progress is 1.0 (100%)- while (true) {- val currentProgress = getAggregateProgress(context, downloadIds)- ds.setDouble("downloadProgress", currentProgress)-- if (currentProgress >= 1.0) break- delay(500) // Check twice a second+ val intent = Intent(context, DownloadService::class.java).apply {+ putExtra("urls", filesToDownload.map { it.first }.toTypedArray())+ putExtra("fileNames", filesToDownload.map { it.second }.toTypedArray()) }-- ds.setBoolean("dbSetupComplete", true)+ context.startForegroundService(intent) } Scaffold { paddingValues ->- Box(- Modifier.padding(paddingValues).fillMaxSize(),- contentAlignment = Alignment.Center+ Column(+ Modifier+ .padding(paddingValues)+ .fillMaxSize()+ .padding(24.dp) ) {- Column(horizontalAlignment = Alignment.CenterHorizontally) {- CircularProgressIndicator(progress = { progress.toFloat() })- Spacer(modifier = Modifier.height(16.dp))- Text("Downloading Initial Data: ${(progress * 100).round(2)}%")+ Text(+ "Initializing System",+ style = MaterialTheme.typography.headlineMedium,+ fontWeight = FontWeight.Bold+ )+ Text(+ "Downloading required AI models and assets via high-speed service.",+ style = MaterialTheme.typography.bodyMedium,+ color = Color.Gray+ )++ Spacer(Modifier.height(32.dp))++ LazyColumn(+ verticalArrangement = Arrangement.spacedBy(20.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ items(filesToDownload) { (url, fileName, desc) ->+ // Each item observes its own specific progress and speed from DataStore+ val progress by ds.doubleFlow("progress_$fileName").collectAsState(0.0)+ val speedMbps by ds.doubleFlow("speed_$fileName").collectAsState(0.0)+ val isDone by ds.booleanFlow("done_$fileName").collectAsState(false)++ FileProgressItem(+ fileName = fileName,+ progress = progress,+ speedMbps = speedMbps,+ isDone = isDone+ )+ } } } } } -private fun getAggregateProgress(context: Context, downloadIds: List<Long>): Double {- if (downloadIds.isEmpty()) return 1.0-- val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager- val query = DownloadManager.Query().setFilterById(*downloadIds.toLongArray())- val cursor = downloadManager.query(query) ?: return 0.0-- var totalBytes = 0L- var downloadedBytes = 0L- var allCompleted = true-- while (cursor.moveToNext()) {- val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))- val bytesDownloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))- val bytesTotal = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))-- if (status != DownloadManager.STATUS_SUCCESSFUL) {- allCompleted = false- }-- if (bytesTotal > 0) {- totalBytes += bytesTotal- downloadedBytes += bytesDownloaded+@Composable+fun FileProgressItem(+ fileName: String,+ progress: Double,+ speedMbps: Double,+ isDone: Boolean+) {+ val animatedProgress by animateFloatAsState(+ targetValue = progress.toFloat(),+ label = "smooth_progress"+ )++ Column(Modifier.fillMaxWidth()) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ fileName,+ style = MaterialTheme.typography.titleSmall,+ modifier = Modifier.weight(1.0f),+ maxLines = 1+ )++ if (!isDone && progress > 0) {+ Surface(+ color = MaterialTheme.colorScheme.secondaryContainer,+ shape = MaterialTheme.shapes.extraSmall+ ) {+ Text(+ text = "${speedMbps.round(1)} Mbps",+ style = MaterialTheme.typography.labelSmall,+ modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),+ color = MaterialTheme.colorScheme.onSecondaryContainer+ )+ }+ } }- }- cursor.close()-- // If totalBytes is still 0 (e.g., pending connection), report 0%- if (totalBytes == 0L) return if (allCompleted) 1.0 else 0.0-- // Ensure we return exactly 1.0 if completed, otherwise a precise ratio- return if (allCompleted) 1.0 else (downloadedBytes.toDouble() / totalBytes)-} -private fun downloadFile(context: Context, url: String, fileName: String, description: String): Long {- val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager+ Spacer(Modifier.height(4.dp)) - // 1. Check if the specific file is already downloading or completed- val query = DownloadManager.Query()- val cursor = downloadManager.query(query)+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ Text(+ text = if (isDone) "Completed" else "Downloading...",+ style = MaterialTheme.typography.labelSmall,+ color = Color.Gray+ ) - if (cursor != null) {- while (cursor.moveToNext()) {- val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))- val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))-- // Check by the specific fileName so we don't mix up the routing binaries- if (title == fileName) {- val id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID))-- // If it's running, pending, or successful, return the existing ID- if (status == DownloadManager.STATUS_RUNNING ||- status == DownloadManager.STATUS_PENDING ||- status == DownloadManager.STATUS_SUCCESSFUL) {- cursor.close()- return id- }- }+ Text(+ text = "${(progress * 100).round(1)}%",+ style = MaterialTheme.typography.labelSmall,+ fontWeight = FontWeight.Bold+ ) }- cursor.close()- } - // 2. If no active/completed download found for this file, start a new one- val request = DownloadManager.Request(url.toUri())- .setTitle(fileName)- .setDescription(description)- .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)- .setDestinationInExternalFilesDir(context, null, fileName)- .setAllowedOverMetered(false) // Wait for WiFi for these massive files- .setRequiresCharging(false)+ Spacer(Modifier.height(8.dp)) - return downloadManager.enqueue(request)+ LinearProgressIndicator(+ progress = { animatedProgress },+ modifier = Modifier.fillMaxWidth().height(6.dp),+ strokeCap = StrokeCap.Round,+ color = if (isDone) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary+ )+ } }\ No newline at end of file
library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex d8c63d85cf..7bef37a3f4 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -48,7 +48,6 @@ class DataStoreUtils private constructor(context: Context) { return stateMap[longPreferencesKey(name)] as Long? } - @Composable fun booleanFlow(name: String): Flow<Boolean> { return dataStore.data.mapNotNull { it[booleanPreferencesKey(name)] } }
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex f97d94421b..d0fd3345dd 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -4,6 +4,9 @@ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> + <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+ <application android:largeHeap="true"@@ -24,6 +27,10 @@ <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>+ <service+ android:name="com.vayunmathur.library.services.DownloadService"+ android:foregroundServiceType="dataSync"+ android:exported="false" /> </application> </manifest>\ No newline at end of file