1package expo.modules.widget
2
3import android.content.Context
4import androidx.glance.appwidget.GlanceAppWidgetManager
5import androidx.glance.appwidget.state.updateAppWidgetState
6import androidx.glance.appwidget.updateAll
7import expo.modules.kotlin.modules.Module
8import expo.modules.kotlin.modules.ModuleDefinition
9import expo.modules.kotlin.records.Field
10import expo.modules.kotlin.records.Record
11import expo.modules.widget.widgets.MyWidget
12import kotlinx.coroutines.CoroutineScope
13import kotlinx.coroutines.Dispatchers
14import kotlinx.coroutines.launch
15import androidx.datastore.preferences.core.stringPreferencesKey
16
17data class WidgetData(
18 @Field val title: String,
19 @Field val subtitle: String
20) : Record
21
22class ExpoWidgetModule : Module() {
23 private val context: Context
24 get() = requireNotNull(appContext.reactContext)
25
26 override fun definition() = ModuleDefinition {
27 Name("ExpoWidgetModule")
28
29 AsyncFunction("updateWidget") { data: WidgetData ->
30 CoroutineScope(Dispatchers.IO).launch {
31 try {
32 val glanceIds = GlanceAppWidgetManager(context)
33 .getGlanceIds(MyWidget::class.java)
34
35 glanceIds.forEach { glanceId ->
36 updateAppWidgetState(context, glanceId) { prefs ->
37 prefs[stringPreferencesKey("widget_title")] = data.title
38 prefs[stringPreferencesKey("widget_subtitle")] = data.subtitle
39 }
40 }
41
42 MyWidget().updateAll(context)
43 } catch (e: Exception) {
44 e.printStackTrace()
45 }
46 }
47 }
48
49 AsyncFunction("refreshWidget") {
50 CoroutineScope(Dispatchers.IO).launch {
51 try {
52 MyWidget().updateAll(context)
53 } catch (e: Exception) {
54 e.printStackTrace()
55 }
56 }
57 }
58 }
59}