如何在应用首次安装24小时后更改布尔配置值?
Hey there! Let's walk through exactly how to set this up for your wallpaper app. Here's a step-by-step breakdown that covers both the default config change and the delayed toggle logic:
false First, update your XML config to set the default state directly:
<bool name="enable_wallpaper_download">false</bool>
You need to record when the app is first installed and schedule a task to flip the toggle 24 hours later. We'll use SharedPreferences to track installation state and WorkManager for the delayed task (it’s far more reliable than AlarmManager, especially with Android 8.0+ background restrictions).
Add this logic to your Application class or first-launched Activity:
// Kotlin example; Java logic is identical with syntax adjustments class MyWallpaperApp : Application() { override fun onCreate() { super.onCreate() val appPrefs = getSharedPreferences("WallpaperAppPrefs", MODE_PRIVATE) val isFirstInstall = appPrefs.getBoolean("is_first_install", true) if (isFirstInstall) { // Mark first install as processed appPrefs.edit().putBoolean("is_first_install", false).apply() // Schedule the 24-hour delay task scheduleDownloadToggle() } } private fun scheduleDownloadToggle() { val delayRequest = OneTimeWorkRequestBuilder<DownloadToggleWorker>() .setInitialDelay(24, TimeUnit.HOURS) .build() WorkManager.getInstance(this).enqueue(delayRequest) } }
You can’t modify XML resources at runtime (they’re read-only), so we’ll store the active toggle state in SharedPreferences. Create a Worker class to update this value after the delay:
class DownloadToggleWorker(context: Context, params: WorkerParameters) : Worker(context, params) { override fun doWork(): Result { val appPrefs = applicationContext.getSharedPreferences("WallpaperAppPrefs", MODE_PRIVATE) // Switch the download toggle to true appPrefs.edit().putBoolean("enable_wallpaper_download", true).apply() return Result.success() } }
Whenever you need to check if downloads are enabled, prioritize the SharedPreferences value (falling back to the XML default if it doesn’t exist):
fun isDownloadEnabled(context: Context): Boolean { val appPrefs = context.getSharedPreferences("WallpaperAppPrefs", MODE_PRIVATE) return appPrefs.getBoolean( "enable_wallpaper_download", context.resources.getBoolean(R.bool.enable_wallpaper_download) ) }
- Uninstall/Reinstall Support: If the user uninstalls and reinstalls the app,
SharedPreferenceswill be cleared, so the 24-hour timer will reset automatically. - Reliability: WorkManager handles device reboots, app force-stops, and system resource constraints—your task will run when the system has available resources.
- Backward Compatibility: WorkManager automatically adapts to older Android versions (pre-8.0) using appropriate underlying APIs, so you don’t need separate logic for different OS levels.
内容的提问来源于stack exchange,提问作者Akinhd

