Android Weekly

Android Weekly #-589 "Android 위젯 라이브러리 - Glance"

베블렌 2023. 9. 25. 03:00

9월 4주차에는 kotlinWeekly에도 나온 Koin 3.5.0 ,3.5.1 이 주요하지만, 개인적으로 이번에 갔다 온 드로이드나이츠에도 나왔고 현재 진행 중인 프로젝트에 쓰일 위젯 라이브러리 Glance가 나와서 작성해 보겠습니다.

 

https://victorbrandalise.com/building-a-widget-using-jetpack-glance/?utm_source=rss&utm_medium=rss&utm_campaign=building-a-widget-using-jetpack-glance 

 

Building a widget using Jetpack Glance by Victor Brandalise

App widgets are miniature application views that can be embedded in the home screen of your device. Jetpack Glance is a library built on top of Jetpack Compose that allows you to build these widgets for Android. In the above image you can see a weather wid

victorbrandalise.com

 

 

소개

 

Glance는Jetpack Compose에서 Android 위젯을 제작하기 라이브러리입니다. (기사글이 굉장히 구독성 떨어지게 작성되어 있긴 합니다)

글에서는 Glance의 세팅방식과 간단한 코드 하나를 보여주고 있습니다.

 

 

내용

 

dependencies {

implementation "androidx.glance:glance:1.0.0-rc01"

implementation "androidx.glance:glance-appwidget:1.0.0-rc01" }

 

아직 따끈따근한 버전인것을 확인할 수 있습니다.

 

  1. res/xml에 app_widget_provider.xml 파일을 생성하여 위젯 공급자를 정의합니다.
  2. QuotesWidget 클래스에서 Glance를 사용하여 위젯의 내용을 제공합니다.
  3. QuotesWidgetReceiver를 생성하여 위젯을 수신합니다.
  4. AndroidManifest.xml에 위에서 만든 수신기를 추가합니다.
  5. Activity가 없는 경우, Android Studio를 수정하여 활동 없이 실행되도록 설정합니다.

 

게시글에서는 명언을 담은 텍스트형식의 위젯을 보여주고있습니다.

 

private val quotes = listOf(
    "Be yourself; everyone else is already taken. ― Oscar Wilde",
    "A room without books is like a body without a soul. ― Marcus Tullius Cicero",
    "You only live once, but if you do it right, once is enough. ― Mae West",
)

private val currentQuoteKey = stringPreferencesKey("currentQuote")

class QuotesWidget : GlanceAppWidget() {

    override val stateDefinition: GlanceStateDefinition<*> = PreferencesGlanceStateDefinition

    override suspend fun provideGlance(context: Context, id: GlanceId) {
        provideContent {
            val preferences = currentState<Preferences>()
            val currentQuote = preferences[currentQuoteKey] ?: quotes.random()

            MaterialTheme {
                Box(
                    modifier = GlanceModifier
                        .background(Color.White)
                        .padding(16.dp)
                        .clickable(actionRunCallback<RefreshQuoteAction>())
                ) {
                    Text(text = currentQuote)
                }
            }
        }
    }

}

class RefreshQuoteAction : ActionCallback {

    override suspend fun onAction(
        context: Context,
        glanceId: GlanceId,
        parameters: ActionParameters
    ) {
        updateAppWidgetState(context, PreferencesGlanceStateDefinition, glanceId) { preferences ->
            preferences.toMutablePreferences().apply {
                this[currentQuoteKey] = quotes.random()
            }
        }
        QuotesWidget().update(context, glanceId)
    }
}

 

생각보다 어렵지 않은 코드라는 것을 볼 수 있습니다.

 

 

 

정리

 

생각보다 글의 내용이 많거나 하진 않았지만 한 번쯤 시도해 보기 좋게 간결하게 작성된 것 같습니다.

위젯에 대해선 안드로이드 공식문서(https://developer.android.com/jetpack/compose/glance/create-app-widget) 에서 확인 할 수 있습니다.
생각보다 간단하게 가능하니 한 번쯤 만들어 보는 것도 좋을 것 같습니다.

 

 

 

 

https://androidweekly.net/

 

Android Weekly - Free weekly Android & Kotlin development newsletter

Android Weekly - Free weekly Android & Kotlin development newsletter

androidweekly.net