57 lines
2.0 KiB
Kotlin
57 lines
2.0 KiB
Kotlin
package de.schanbro.weekfocus
|
|
|
|
import android.appwidget.AppWidgetManager
|
|
import android.appwidget.AppWidgetProvider
|
|
import android.content.Context
|
|
import android.widget.RemoteViews
|
|
import androidx.compose.ui.res.stringResource
|
|
import java.util.Calendar
|
|
import java.util.Random
|
|
|
|
class SimpleWidget : AppWidgetProvider() {
|
|
|
|
override fun onUpdate(
|
|
context: Context,
|
|
appWidgetManager: AppWidgetManager,
|
|
appWidgetIds: IntArray
|
|
) {
|
|
for (appWidgetId in appWidgetIds) {
|
|
updateAppWidget(context, appWidgetManager, appWidgetId)
|
|
}
|
|
}
|
|
|
|
companion object {
|
|
fun updateAppWidget(
|
|
context: Context,
|
|
appWidgetManager: AppWidgetManager,
|
|
appWidgetId: Int
|
|
) {
|
|
// 1. SharedPreferences auslesen
|
|
val sharedPrefs = context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
|
|
val savedSet = sharedPrefs.getStringSet("words_key", emptySet()) ?: emptySet()
|
|
val wordList = savedSet.toList()
|
|
|
|
// 2. Aktuelle Kalenderwoche & Jahr bestimmen
|
|
val calendar = Calendar.getInstance()
|
|
val weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR)
|
|
val year = calendar.get(Calendar.YEAR)
|
|
|
|
// 3. Wort für die aktuelle Kalenderwoche auswählen
|
|
val displayText = if (wordList.isNotEmpty()) {
|
|
// Kombinierter Seed aus Jahr und Kalenderwoche
|
|
val seed = (year * 100 + weekOfYear).toLong()
|
|
val random = Random(seed)
|
|
val randomIndex = random.nextInt(wordList.size)
|
|
wordList[randomIndex]
|
|
} else {
|
|
context.getString(R.string.msg_no_words)
|
|
}
|
|
|
|
// 4. RemoteViews aktualisieren
|
|
val views = RemoteViews(context.packageName, R.layout.widget_main)
|
|
views.setTextViewText(R.id.appwidget_text, displayText)
|
|
|
|
appWidgetManager.updateAppWidget(appWidgetId, views)
|
|
}
|
|
}
|
|
} |