package com.rnwallpapers import android.content.Context import android.graphics.BitmapFactory import android.os.Build import androidx.work.* import java.io.File import java.net.HttpURLConnection import java.net.URL import java.util.concurrent.TimeUnit class AutoChangeWorker( private val context: Context, workerParams: WorkerParameters ) : CoroutineWorker(context, workerParams) { override suspend fun doWork(): Result { return try { val prefs = context.getSharedPreferences("RNWallpapers", Context.MODE_PRIVATE) if (!prefs.getBoolean("auto_active", false)) { return Result.success() } val sources = prefs.getStringSet("auto_sources", emptySet())?.toList() ?: return Result.failure() if (sources.isEmpty()) return Result.failure() val shuffle = prefs.getBoolean("auto_shuffle", false) var index = prefs.getInt("auto_index", 0) val target = prefs.getString("auto_target", "home") ?: "home" // Pick next source val source = if (shuffle) { sources.random() } else { val current = sources[index % sources.size] index = (index + 1) % sources.size prefs.edit().putInt("auto_index", index).apply() current } // Download and set val bitmap = if (source.startsWith("http")) { val conn = URL(source).openConnection() as HttpURLConnection conn.connect() BitmapFactory.decodeStream(conn.inputStream) } else { BitmapFactory.decodeFile(source.removePrefix("file://")) } ?: return Result.retry() val wallpaperManager = android.app.WallpaperManager.getInstance(context) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val flag = when (target) { "home" -> android.app.WallpaperManager.FLAG_SYSTEM "lock" -> android.app.WallpaperManager.FLAG_LOCK else -> android.app.WallpaperManager.FLAG_SYSTEM or android.app.WallpaperManager.FLAG_LOCK } wallpaperManager.setBitmap(bitmap, null, true, flag) } else { wallpaperManager.setBitmap(bitmap) } // Save last set info prefs.edit().apply { putString("last_set_target", target) putString("last_set_type", "static") putString("last_set_path", source) putLong("last_set_at", System.currentTimeMillis()) apply() } Result.success() } catch (e: Exception) { Result.retry() } } companion object { private const val WORK_TAG = "RNWallpapers_AutoChange" fun schedule(context: Context, intervalMinutes: Long) { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val request = PeriodicWorkRequestBuilder( intervalMinutes, TimeUnit.MINUTES ) .setConstraints(constraints) .addTag(WORK_TAG) .setBackoffCriteria(BackoffPolicy.LINEAR, 15, TimeUnit.MINUTES) .build() WorkManager.getInstance(context).enqueueUniquePeriodicWork( WORK_TAG, ExistingPeriodicWorkPolicy.UPDATE, request ) } fun cancel(context: Context) { WorkManager.getInstance(context).cancelAllWorkByTag(WORK_TAG) } } }