Вот мой код
Код: Выделить всё
private const val USER_PREFERENCES = "user_preferences"
@Module
@InstallIn(SingletonComponent::class)
object DataStoreModule {
@Provides
@Singleton
fun provideDataStore(@ApplicationContext context: Context): DataStore
{
return PreferenceDataStoreFactory.create (
produceFile = { context.preferencesDataStoreFile(USER_PREFERENCES) }
)
}
@Provides
@Singleton
fun provideDataStoreRepository(dataStore: DataStore): DataStoreRepository {
return DataStoreRepository(dataStore)
}
}
@Singleton
class DataStoreRepository @Inject constructor(private val dataStore: DataStore) {
private object PreferencesKeys {
val COUNTER_KEY = intPreferencesKey("counter_key")
}
// Get the current counter value as a Flow
val counterFlow: Flow = dataStore.data
.map { preferences ->
preferences[PreferencesKeys.COUNTER_KEY] ?: 0 // Default to 0 if no value is stored
}
// Increment the counter value
suspend fun incrementCounter() {
dataStore.edit { preferences ->
val currentValue = preferences[PreferencesKeys.COUNTER_KEY] ?: 0
preferences[PreferencesKeys.COUNTER_KEY] = currentValue + 1
}
}
}
class MyWidget: GlanceAppWidget() {
override val sizeMode = SizeMode.Exact
override suspend fun provideGlance(context: Context, id: GlanceId) {
provideContent {
GlanceTheme {
val dataStore = PreferenceDataStoreFactory.create {
context.preferencesDataStoreFile("user_preferences")
}
val size = LocalSize.current
val dataStoreRepository = remember { DataStoreRepository(dataStore) }
val counter by dataStoreRepository.counterFlow.collectAsState(initial = 0)
Scaffold(
titleBar = {
TitleBar(startIcon = ImageProvider(R.mipmap.ic_launcher), title = "Hello")
}, backgroundColor = GlanceTheme.colors.widgetBackground
) {
Column(
modifier = GlanceModifier.background(color = Color.Red)
.padding(30.dp)
) {
Text(
text = "Counter value is ${counter}",
style = TextStyle(
color = ColorProvider(
color = Color(0xFF000000)
),
fontSize = 12.sp,
fontWeight = FontWeight.Medium
),
modifier = GlanceModifier.clickable {
actionStartActivity(activity = MainActivity::class.java)
}
)
Button("Start Activity", onClick = actionStartActivity(), style = TextStyle(
color = ColorProvider(
color = Color(0x00FF0000)
),
fontSize = 12.sp,
fontWeight = FontWeight.Medium
),)
}
}
}
}
}
override fun onCompositionError(
context: Context,
glanceId: GlanceId,
appWidgetId: Int,
throwable: Throwable
) {
super.onCompositionError(context, glanceId, appWidgetId, throwable)
val remoteView = RemoteViews(context.packageName, R.layout.custom_error_layout)
Log.i("errorMessageis","${throwable.message} ${throwable.localizedMessage}")
remoteView.setTextViewText(R.id.textview,"${throwable.message} ${throwable.localizedMessage}")
AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteView)
}
}
Я пытался изучить GlanceStateDefinition
code> тоже, но проблема с GlanceStateDefinition в том, что я не могу обновить GlanceStateDefinition до тех пор, пока пользователь не создаст виджет и впервые данные GlanceStateDefinition не будут пустыми. В моем приложении, если бы у меня была кнопка и при нажатии на нее я вызывал бы приведенный ниже код
Код: Выделить всё
CoroutineScope(Dispatchers.IO).launch {
val glanceIds =
GlanceAppWidgetManager(this@MainActivity).getGlanceIds(MyWidget::class.java)
glanceIds.forEach { id ->
updateAppWidgetState(this@MainActivity, id) {
it[longPreferencesKey("now")] = System.currentTimeMillis()
}
MyWidget().update(this@MainActivity, id)
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... -jetpack-g
Мобильная версия