Skip to content

Instantly share code, notes, and snippets.

@kartikarora
Created October 24, 2024 23:07
Show Gist options
  • Save kartikarora/b1429dda6381c02c89c51490cc6aadc1 to your computer and use it in GitHub Desktop.
Save kartikarora/b1429dda6381c02c89c51490cc6aadc1 to your computer and use it in GitHub Desktop.
Activity 9 Step 1
class QuoteWidgetWorker(
private val context: Context,
params: WorkerParameters,
) : CoroutineWorker(context, params) {
companion object {
private val uniqueWorkName = QuoteWidgetWorker::class.java.simpleName
fun enqueue(context: Context, force: Boolean = false) {
val workManager = WorkManager.getInstance(context)
val request =
PeriodicWorkRequestBuilder<QuoteWidgetWorker>(15, TimeUnit.MINUTES).build()
workManager.enqueueUniquePeriodicWork(
uniqueWorkName = uniqueWorkName,
existingPeriodicWorkPolicy = if (force) {
ExistingPeriodicWorkPolicy.UPDATE
} else {
ExistingPeriodicWorkPolicy.KEEP
},
request = request
)
}
fun cancel(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(uniqueWorkName)
}
}
override suspend fun doWork(): Result {
val geminiInterface = GeminiInterface()
val appWidgetManager = GlanceAppWidgetManager(context)
// Fetch the current state of each widget, get the current topic, fetch a new quote and update the state
appWidgetManager.getGlanceIds(QuoteWidget::class.java).forEach { glanceId ->
val currentWidgetState =
getAppWidgetState(context, PreferencesGlanceStateDefinition, glanceId)
val currentTopicName = currentWidgetState[KEY_TOPIC]
val generatedQuote = geminiInterface.getSingleQuote(currentTopicName)
val newQuote = sampleData.firstOrNull {
it.name == currentTopicName
}?.quotes?.random() ?: generatedQuote
// Update the widget with this new state
updateAppWidgetState(context, glanceId) { prefs ->
prefs[KEY_QUOTE] = newQuote?.text ?: "Quote not found"
}
// Let the widget know there is a new state so it updates the UI
QuoteWidget().update(context, glanceId)
}
return Result.success()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment