glance: publish generated widget-picker previews once per app version
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package de.jeanlucmakiola.floret.glance
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.core.content.edit
|
||||
import androidx.glance.appwidget.GlanceAppWidgetManager
|
||||
import androidx.glance.appwidget.GlanceAppWidgetReceiver
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
private const val PREFS = "floret_widget_previews"
|
||||
|
||||
/**
|
||||
* Publishes each receiver's generated widget-picker preview (its widget's
|
||||
* `providePreview`) once per [version] (an app update, say), on Android 15+; below that the
|
||||
* provider's `previewLayout` stays the picker's preview. A receiver the system
|
||||
* rate-limits, or whose preview fails, is retried on the next call.
|
||||
*/
|
||||
suspend fun publishWidgetPreviews(
|
||||
context: Context,
|
||||
version: String,
|
||||
receivers: List<KClass<out GlanceAppWidgetReceiver>>,
|
||||
) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) return
|
||||
val appContext = context.applicationContext
|
||||
val prefs = appContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
val manager = GlanceAppWidgetManager(appContext)
|
||||
receivers.forEach { receiver ->
|
||||
val key = receiver.java.name
|
||||
if (prefs.getString(key, null) == version) return@forEach
|
||||
try {
|
||||
if (manager.setWidgetPreviews(receiver) == GlanceAppWidgetManager.SET_WIDGET_PREVIEWS_RESULT_SUCCESS) {
|
||||
prefs.edit { putString(key, version) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w("FloretWidgets", "Publishing the preview of $key failed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user