Created
October 24, 2024 23:07
-
-
Save kartikarora/b1429dda6381c02c89c51490cc6aadc1 to your computer and use it in GitHub Desktop.
Activity 9 Step 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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