다음 섹션에서는 GlanceAppWidget를 업데이트하고 상태를 관리하는 방법을 설명합니다.
GlanceAppWidget 상태 관리
제공된 GlanceAppWidget 클래스는 위젯이 생성되거나 업데이트가 필요할 때마다 인스턴스화되므로 상태가 없고 수동적이어야 합니다.
상태 개념은 다음과 같이 나눌 수 있습니다.
애플리케이션 상태: 위젯에 필요한 앱의 상태 또는 콘텐츠입니다. 예를 들어 사용자가 정의한 저장된 대상 목록 (즉, 데이터베이스)입니다.
글랜스 상태: 앱 위젯에만 관련이 있고 앱의 상태를 수정하거나 영향을 주지 않는 특정 상태입니다. 예를 들어 위젯에서 체크박스가 선택되었거나 카운터가 증가했습니다.
애플리케이션 상태 사용
앱 위젯은 수동적이어야 합니다. 각 애플리케이션은 데이터 레이어를 관리하고 위젯 UI에 반영되는 유휴, 로드, 오류와 같은 상태를 처리해야 합니다.
예를 들어 다음 코드는 저장소 레이어의 인메모리 캐시에서 목적지를 가져오고, 저장된 목적지 목록을 제공하고, 상태에 따라 다른 UI를 표시합니다.
classDestinationAppWidget:GlanceAppWidget(){// ...@ComposablefunMyContent(){valrepository=remember{DestinationsRepository.getInstance()}// Retrieve the cache data everytime the content is refreshedvaldestinationsbyrepository.destinations.collectAsState(State.Loading)when(destinations){isState.Loading->{// show loading content}isState.Error->{// show widget error content}isState.Completed->{// show the list of destinations}}}}
상태나 데이터가 변경될 때마다 앱은 위젯에 알리고 위젯을 업데이트해야 합니다. 자세한 내용은 GlanceAppWidget 업데이트를 참고하세요.
GlanceAppWidget 업데이트
GlanceAppWidget를 사용하여 위젯 콘텐츠를 업데이트하도록 요청할 수 있습니다. GlanceAppWidget 상태 관리 섹션에 설명된 대로 앱 위젯은 다른 프로세스에서 호스팅됩니다. Glance는 콘텐츠를 실제 RemoteViews로 변환하여 호스트에 전송합니다. 콘텐츠를 업데이트하려면 Glance에서 RemoteViews를 다시 만들어 다시 전송해야 합니다.
// Updates all placed instances of MyAppWidgetMyAppWidget().updateAll(context)// Iterate over all placed instances of MyAppWidget and update if the state of// the instance matches the given predicateMyAppWidget().updateIf<State>(context){state->
state==State.Completed}
이러한 메서드는 애플리케이션의 어느 부분에서든 호출할 수 있습니다. suspend 함수이므로 기본 스레드 범위 외부에서 실행하는 것이 좋습니다. 다음 예에서는 CoroutineWorker에서 실행됩니다.
classDataSyncWorker(valcontext:Context,valparams:WorkerParameters,):CoroutineWorker(context,params){overridesuspendfundoWork():Result{// Fetch data or do some work and then update all instance of your widgetMyAppWidget().updateAll(context)returnResult.success()}}
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-25(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-25(UTC)"],[],[],null,["The following sections describe how to update `GlanceAppWidget` and manage its\nstate.\n\nManage `GlanceAppWidget` state\n\nThe provided `GlanceAppWidget` class is instantiated whenever the widget is\ncreated or requires an update, so it should be *stateless and passive*.\n| **Key Point:** App widgets live in a different process. While the defined UI content (meaning the underlying `RemoteViews`) is restored by the system, any state kept in-memory, for example in the app's scope, can be destroyed at any time.\n\nThe concept of state can be divided into the following:\n\n- **Application state**: The state or content of the app that is required by the widget. For example, a list of stored destinations (i.e., database) defined by the user.\n- **Glance state**: The specific state that is only relevant to the app widget and does not necessarily modify or affect the app's state. For example, a checkbox was selected in the widget or a counter was increased.\n\nUse application state\n\nApp widgets should be passive. Each application is responsible for managing the\ndata layer and handling the states, such as idle, loading, and error reflecting\nin the widget UI.\n\nFor example, the following code retrieves the destinations from the in-memory\ncache from the repository layer, provides the stored list of destinations, and\ndisplays a different UI depending on its state:\n\n\n```kotlin\nclass DestinationAppWidget : GlanceAppWidget() {\n\n // ...\n\n @Composable\n fun MyContent() {\n val repository = remember { DestinationsRepository.getInstance() }\n // Retrieve the cache data everytime the content is refreshed\n val destinations by repository.destinations.collectAsState(State.Loading)\n\n when (destinations) {\n is State.Loading -\u003e {\n // show loading content\n }\n\n is State.Error -\u003e {\n // show widget error content\n }\n\n is State.Completed -\u003e {\n // show the list of destinations\n }\n }\n }\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L368-L392\n```\n\n\u003cbr /\u003e\n\nWhenever the state or the data changes, it is the app's responsibility to notify\nand update the widget. See [Update GlanceAppWidget](/develop/ui/compose/glance/glance-app-widget#update-glance-appwidget) for more information.\n| **Note:** See the [Optimizations for updating widget content](/guide/topics/appwidgets/advanced#update-widgets) section in the app widgets guide to understand how and when to update.\n\nUpdate `GlanceAppWidget`\n\nYou can request to update your widget content using `GlanceAppWidget`. As\nexplained in the [Manage `GlanceAppWidget` state](#manage-state) section, app\nwidgets are hosted in a different process. Glance translates the content into\nactual `RemoteViews` and sends them to the host. To update the content, Glance\nmust recreate the `RemoteViews` and send them again.\n\nTo send the update, call the `update` method of the `GlanceAppWidget` instance,\nproviding the `context` and the `glanceId`:\n\n\n```kotlin\nMyAppWidget().update(context, glanceId)https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L397-L397\n```\n\n\u003cbr /\u003e\n\nTo obtain the `glanceId`, query the `GlanceAppWidgetManager`:\n\n\n```kotlin\nval manager = GlanceAppWidgetManager(context)\nval widget = GlanceSizeModeWidget()\nval glanceIds = manager.getGlanceIds(widget.javaClass)\nglanceIds.forEach { glanceId -\u003e\n widget.update(context, glanceId)\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L401-L406\n```\n\n\u003cbr /\u003e\n\nAlternatively, use one of the `GlanceAppWidget update` extensions:\n\n\n```kotlin\n// Updates all placed instances of MyAppWidget\nMyAppWidget().updateAll(context)\n\n// Iterate over all placed instances of MyAppWidget and update if the state of\n// the instance matches the given predicate\nMyAppWidget().updateIf\u003cState\u003e(context) { state -\u003e\n state == State.Completed\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L410-L417\n```\n\n\u003cbr /\u003e\n\nThese methods can be called from any part of your application. Because they are\n`suspend` functions, we recommend launching them outside of the main thread\nscope. In the following example, they are launched in a `CoroutineWorker`:\n\n\n```kotlin\nclass DataSyncWorker(\n val context: Context,\n val params: WorkerParameters,\n) : CoroutineWorker(context, params) {\n\n override suspend fun doWork(): Result {\n // Fetch data or do some work and then update all instance of your widget\n MyAppWidget().updateAll(context)\n return Result.success()\n }\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L422-L432\n```\n\n\u003cbr /\u003e\n\nSee [Kotlin Coroutines on Android](/kotlin/coroutines) for more details on coroutines.\n\nWhen to update widgets\n\nUpdate widgets either immediately or periodically.\n\nYour widget can update immediately when your app is awake. For example:\n\n- When a user interacts with a widget, triggering an action, a lambda call, or an intent to launch an activity.\n- When your user interacts with your app in the foreground, or while the app is already updating in response to a Firebase Cloud Messaging (FCM) message or a broadcast.\n\nIn these cases, call the [`update`](/reference/kotlin/androidx/glance/appwidget/GlanceAppWidget#update(android.content.Context,androidx.glance.GlanceId)) method as described in this guide.\n\nYour widget can update periodically when your app isn't awake. For example:\n\n- Use [`updatePeriodMillis`](/reference/android/appwidget/AppWidgetProviderInfo#updatePeriodMillis) to update the widget up to once every 30 minutes.\n- Use `WorkManager` to schedule more frequent updates, such as every 15 minutes.\n- Update the widget in response to a broadcast.\n\n| **Important:** Avoid updating your widget every minute when the app isn't awake, as frequent updates drain your users' battery.\n\nResources\n\n- [Create a widget with Glance](/codelabs/glance) (Codelab)\n- [Building for the Future of Android: Widgets chapter](https://www.youtube.com/watch?v=YKPqjsYBFvI&t=487s) (Video)"]]