Keep storage and image decoding off the main thread at start-up

This commit is contained in:
2026-10-31 11:50:13 +02:00
parent 6444a81f95
commit d58e9cb5f9
6 changed files with 67 additions and 34 deletions
@@ -40,6 +40,7 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
@@ -126,7 +127,7 @@ private fun AboutContent(modifier: Modifier, onOpenLicenses: () -> Unit) {
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
Image( Image(
painterResource(R.drawable.app_logo), remember { AppLogo.get(context) },
contentDescription = null, contentDescription = null,
modifier = Modifier modifier = Modifier
.size(104.dp) .size(104.dp)
@@ -72,7 +72,10 @@ object Blocklist {
fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes) fun isBlocked(name: String): Boolean = _enabled.value && isBlockedIn(name, listHashes, customHashes)
fun reload(context: Context) = synchronized(lock) { load(BlocklistStore(context)) } // Reads the saved lists unless something did already, such as the background update job
fun ensureLoaded(context: Context) {
synchronized(lock) { ensureLoaded(BlocklistStore(context)) }
}
fun setEnabled(context: Context, value: Boolean) { fun setEnabled(context: Context, value: Boolean) {
BlocklistStore(context).enabled = value BlocklistStore(context).enabled = value
@@ -329,8 +332,12 @@ private fun LongArray.sortUnique(): LongArray {
} }
private class BlocklistStore(context: Context) { private class BlocklistStore(context: Context) {
private val dir = File(context.filesDir, "blocklist").apply { mkdirs() } private val appContext = context.applicationContext
private val sp = context.getSharedPreferences("blocklist", Context.MODE_PRIVATE)
// Created on first use: switching blocking on or off, which happens on the main thread,
// touches only the settings
private val dir by lazy { File(appContext.filesDir, "blocklist").apply { mkdirs() } }
private val sp = appContext.getSharedPreferences("blocklist", Context.MODE_PRIVATE)
var enabled: Boolean var enabled: Boolean
get() = sp.getBoolean("enabled", true) get() = sp.getBoolean("enabled", true)
@@ -5,6 +5,8 @@ import android.content.Context
import android.os.Build import android.os.Build
import android.os.Process import android.os.Process
import android.os.StrictMode import android.os.StrictMode
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File import java.io.File
import java.io.PrintWriter import java.io.PrintWriter
import java.io.StringWriter import java.io.StringWriter
@@ -17,22 +19,25 @@ class SparkleApp : Application() {
Thread({ Thread({
// Reads what the first screen needs before it asks, so its first frame does not wait on storage // Reads what the first screen needs before it asks, so its first frame does not wait on storage
Prefs(this).providerId Prefs(this).providerId
CrashLog.preload(this) CrashLog.load(this)
StatsStore.init(this) StatsStore.init(this)
// Older versions cached a server list downloaded from the repository // Older versions cached a server list downloaded from the repository
File(filesDir, "servers.txt").delete() File(filesDir, "servers.txt").delete()
AutoUpdate.apply(this) AutoUpdate.apply(this)
// Lists can hold millions of entries; loading them should not take CPU from the first frames // Lists can hold millions of entries; loading them should not take CPU from the first frames
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND) Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
runCatching { Blocklist.reload(this) } runCatching { Blocklist.ensureLoaded(this) }
}, "startup-load").start() }, "startup-load").start()
} }
// The VPN keeps the process running long after the screens are gone; decoded app icons // The VPN keeps the process running long after the screens are gone; decoded app icons
// (up to 10 MB) can be rendered again the next time the Apps tab opens // (up to 10 MB) and the logo can be rendered again the next time they are shown
override fun onTrimMemory(level: Int) { override fun onTrimMemory(level: Int) {
super.onTrimMemory(level) super.onTrimMemory(level)
if (level >= TRIM_MEMORY_UI_HIDDEN) clearAppIconCache() if (level >= TRIM_MEMORY_UI_HIDDEN) {
clearAppIconCache()
AppLogo.clear()
}
} }
// Debug builds only: logs disk and network access on the main thread, leaked closeables and the like // Debug builds only: logs disk and network access on the main thread, leaked closeables and the like
@@ -46,13 +51,18 @@ class SparkleApp : Application() {
object CrashLog { object CrashLog {
private const val FILE_NAME = "last_crash.txt" private const val FILE_NAME = "last_crash.txt"
// Null when there is no report, and until the startup thread has read it
private val _report = MutableStateFlow<String?>(null)
val report: StateFlow<String?> = _report
fun install(context: Context) { fun install(context: Context) {
val file = File(context.filesDir, FILE_NAME) val appContext = context.applicationContext
val previous = Thread.getDefaultUncaughtExceptionHandler() val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, error -> Thread.setDefaultUncaughtExceptionHandler { thread, error ->
runCatching { runCatching {
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString() val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
file.writeText( // Looked up only now: install() runs on the main thread at start-up
File(appContext.filesDir, FILE_NAME).writeText(
"Thread: ${thread.name}\n" + "Thread: ${thread.name}\n" +
"Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT}), " + "Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT}), " +
"${Build.MANUFACTURER} ${Build.MODEL}\n\n$trace" "${Build.MANUFACTURER} ${Build.MODEL}\n\n$trace"
@@ -62,24 +72,14 @@ object CrashLog {
} }
} }
@Volatile // Runs on the startup thread, so the main thread never reads the file
private var preloaded = false fun load(context: Context) {
_report.value = runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
@Volatile
private var report: String? = null
fun preload(context: Context) {
report = load(context)
preloaded = true
} }
fun read(context: Context): String? = if (preloaded) report else load(context)
fun clear(context: Context) { fun clear(context: Context) {
report = null _report.value = null
File(context.filesDir, FILE_NAME).delete() val appContext = context.applicationContext
Thread({ File(appContext.filesDir, FILE_NAME).delete() }, "crash-clear").start()
} }
private fun load(context: Context): String? =
runCatching { File(context.filesDir, FILE_NAME).takeIf { it.exists() }?.readText() }.getOrNull()
} }
@@ -131,8 +131,8 @@ fun HomeScreen(
val shown = active ?: selected val shown = active ?: selected
val usesHttp3 = shown.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE val usesHttp3 = shown.http3 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
val crashReport = remember { CrashLog.read(context) } val crashReport by CrashLog.report.collectAsStateWithLifecycle()
var crashVisible by remember { mutableStateOf(crashReport != null) } val shownReport = rememberLast(crashReport).orEmpty() // kept while the card animates out
// Strict Private DNS makes Android ignore the VPN's DNS server; followed while Home is visible // Strict Private DNS makes Android ignore the VPN's DNS server; followed while Home is visible
val privateDnsHost by remember { privateDnsHosts(context) }.collectAsStateWithLifecycle(initialValue = null) val privateDnsHost by remember { privateDnsHosts(context) }.collectAsStateWithLifecycle(initialValue = null)
@@ -262,22 +262,21 @@ fun HomeScreen(
verticalArrangement = Arrangement.spacedBy(20.dp), verticalArrangement = Arrangement.spacedBy(20.dp),
) { ) {
Image( Image(
painterResource(R.drawable.app_logo), remember { AppLogo.get(context) },
contentDescription = null, contentDescription = null,
modifier = Modifier modifier = Modifier
.size(44.dp) .size(44.dp)
.align(Alignment.CenterHorizontally), .align(Alignment.CenterHorizontally),
) )
AnimatedVisibility(visible = crashVisible, enter = Motion.expandIn, exit = Motion.collapseOut) { AnimatedVisibility(visible = crashReport != null, enter = Motion.expandIn, exit = Motion.collapseOut) {
val report = crashReport.orEmpty()
CrashCard( CrashCard(
report = report, report = shownReport,
onCopy = { onCopy = {
context.getSystemService(ClipboardManager::class.java) context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", report)) .setPrimaryClip(ClipData.newPlainText("SparkleDNS crash", shownReport))
}, },
onDismiss = { CrashLog.clear(context); crashVisible = false }, onDismiss = { CrashLog.clear(context) },
) )
} }
@@ -51,6 +51,7 @@ import kotlinx.coroutines.flow.flowOf
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
AppLogo.preload(this)
enableEdgeToEdge() enableEdgeToEdge()
setContent { setContent {
MaterialTheme(colorScheme = AppColors) { AppShell() } MaterialTheme(colorScheme = AppColors) { AppShell() }
@@ -1,5 +1,6 @@
package cc.skysparkle.sparkledns package cc.skysparkle.sparkledns
import android.content.Context
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.compose.foundation.background import androidx.compose.foundation.background
@@ -32,6 +33,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
@@ -48,6 +51,28 @@ import java.util.Locale
val CachedColor = Color(0xFF7FD1AE) val CachedColor = Color(0xFF7FD1AE)
val WarningColor = Color(0xFFFFB86B) val WarningColor = Color(0xFFFFB86B)
// The 512 px logo, decoded once while the screens are in use. Home shows it each time the tab
// opens, and decoding it there would cost the main thread a frame.
object AppLogo {
@Volatile
private var bitmap: ImageBitmap? = null
// Started with the activity, so the first frame of Home usually finds the logo decoded
fun preload(context: Context) {
if (bitmap != null) return
val appContext = context.applicationContext
Thread({ runCatching { get(appContext) } }, "logo-load").start()
}
@Synchronized
fun get(context: Context): ImageBitmap =
bitmap ?: ImageBitmap.imageResource(context.resources, R.drawable.app_logo).also { bitmap = it }
fun clear() {
bitmap = null
}
}
// Icon on a soft circle of its own color // Icon on a soft circle of its own color
@Composable @Composable
fun IconBadge(@DrawableRes icon: Int, tint: Color = MaterialTheme.colorScheme.primary, size: Dp = 40.dp) { fun IconBadge(@DrawableRes icon: Int, tint: Color = MaterialTheme.colorScheme.primary, size: Dp = 40.dp) {