위젯 시작하기

기본 요건 및 설정

시작하기 전에 환경이 다음 요구사항을 충족하는지 확인하세요.

런타임 요구사항

Wear 위젯에는 대상 기기에 com.google.android.wearable.protolayout.renderer APK 버전 1.6.1 이상 이 필요합니다.

다음 방법 중 하나로 호환되는 버전의 렌더러를 가져옵니다.

  • Wear OS 7 에뮬레이터: Wear OS 7 에뮬레이터 이미지를 사용합니다. 7보다 낮은 버전은 적합하지 않습니다. 설정 안내는 Wear OS 7 에뮬레이터 설정을 참고하세요.
  • 실제 기기: Google Play 스토어에서 자동 업데이트를 수신하는 실제 Wear OS 기기 또는 Google Play 스토어에 로그인한 개발자 기기를 사용합니다.

기기에 설치된 버전을 확인하려면 다음 명령어를 사용하세요.

adb shell dumpsys package com.google.android.wearable.protolayout.renderer | \
  grep -m 1 versionName | \
  awk -F= '{print $2}'

Gradle 구성

Wear 위젯 라이브러리는 Google Maven 에서 사용할 수 있습니다.

1. SDK 버전 구성

compileSdktargetSdk37 이상으로 설정되어 있는지 확인합니다.

android {
    compileSdk = 37
    // ...
    defaultConfig {
        targetSdk = 37
        // ...
    }
}

2. 종속 항목을 추가합니다.

앱의 build.gradle.kts 파일에 다음 종속 항목을 포함합니다.

Groovy

dependencies {
    // Core Wear Widget and Remote Compose libraries
    implementation "androidx.compose.remote:remote-creation-compose:1.0.0-alpha010"
    implementation "androidx.compose.remote:remote-core:1.0.0-alpha010"
    implementation "androidx.glance.wear:wear:1.0.0-alpha09"
    implementation "androidx.glance.wear:wear-core:1.0.0-alpha09"
    implementation "androidx.wear.compose.remote:remote-material3:1.0.0-alpha03"

    // Tooling for previews (optional, but recommended)
    implementation "androidx.compose.remote:remote-tooling-preview:1.0.0-alpha010"
    implementation "androidx.wear.compose:compose-ui-tooling:1.6.1"
    implementation "androidx.wear.tiles:tiles-tooling-preview:1.6.0"
    debugImplementation "androidx.wear.tiles:tiles-renderer:1.6.0"
}

Kotlin

dependencies {
    // Core Wear Widget and Remote Compose libraries
    implementation("androidx.compose.remote:remote-creation-compose:1.0.0-alpha010")
    implementation("androidx.compose.remote:remote-core:1.0.0-alpha010")
    implementation("androidx.glance.wear:wear:1.0.0-alpha09")
    implementation("androidx.glance.wear:wear-core:1.0.0-alpha09")
    implementation("androidx.wear.compose.remote:remote-material3:1.0.0-alpha03")

    // Tooling for previews (optional, but recommended)
    implementation("androidx.compose.remote:remote-tooling-preview:1.0.0-alpha010")
    implementation("androidx.wear.compose:compose-ui-tooling:1.6.1")
    implementation("androidx.wear.tiles:tiles-tooling-preview:1.6.0")
    debugImplementation("androidx.wear.tiles:tiles-renderer:1.6.0")
}

Hello World 위젯 빌드

Wear 위젯은 GlanceWearWidgetService를 확장하는 서비스와 GlanceWearWidget를 확장하는 위젯 클래스로 구성됩니다. UI는 @RemoteComposable 함수를 사용하여 정의됩니다. @RemoteComposable 함수.

서비스 정의

서비스는 시스템이 바인딩하는 진입점입니다.

위젯을 정의하려면 GlanceWearWidgetService를 확장하는 서비스를 만듭니다. 이 라이브러리는 활발히 개발 중이므로 최종 이름과 구조가 다듬어지는 동안 특정 API가 제한됩니다. Using the @SuppressLint("RestrictedApi") annotation tells your compiler that you are intentionally using these new, evolving features. 이 요구사항은 일시적이며 향후 안정적인 출시 버전에서 API가 완료되면 삭제됩니다.

@SuppressLint("RestrictedApi")
class HelloWidgetService : GlanceWearWidgetService() {
    override val widget: GlanceWearWidget = HelloWidget()
}

위젯 정의

위젯 클래스는 위젯의 데이터와 레이아웃을 제공합니다.

@SuppressLint("RestrictedApi")
class HelloWidget : GlanceWearWidget() {
    override suspend fun provideWidgetData(
        context: Context,
        params: WearWidgetParams,
    ): WearWidgetData {
        return WearWidgetDocument(background = WearWidgetBrush.color(Color.Blue.rc)) {
            HelloWidgetContent()
        }
    }
}

콘텐츠 정의

콘텐츠는 원격 Compose 구성요소를 사용하여 빌드됩니다.

@SuppressLint("RestrictedApi")
@RemoteComposable @Composable
fun HelloWidgetContent() {
    RemoteBox(
        modifier = RemoteModifier.fillMaxSize(),
        contentAlignment = RemoteAlignment.Center,
    ) {
        RemoteText(
            text = "Hello World",
            color = Color.White.rc
        )
    }
}

위젯 구성 XML 만들기

새 파일 res/xml/hello_widget_info.xml을 만들어 위젯의 속성과 지원되는 크기를 정의합니다. <wearwidget-provider> 태그에서 지원되는 XML 속성의 전체 참조는 WearWidgetProviderInfo 문서를 참고하세요.

<wearwidget-provider
    description="@string/hello_widget_description"
    icon="@mipmap/ic_launcher"
    label="@string/hello_widget_label"
    preferredType="SMALL">

    <container
        type="SMALL"
        previewImage="@drawable/widget_preview_small" />
    <container
        type="LARGE"
        previewImage="@drawable/widget_preview_large" />
</wearwidget-provider>

AndroidManifest.xml에 등록

필요한 인텐트 필터와 메타데이터를 사용하여 AndroidManifest.xml에 서비스를 등록합니다.

<service
    android:name=".snippets.widget.HelloWidgetService"
    android:exported="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/hello_widget_label"
    android:permission="com.google.android.wearable.permission.BIND_TILE_PROVIDER">

    <intent-filter>
        <action android:name="androidx.glance.wear.action.BIND_WIDGET_PROVIDER" />
        <!-- If you already have a Tile, omit the following line. -->
        <action android:name="androidx.wear.tiles.action.BIND_TILE_PROVIDER" />
    </intent-filter>

    <meta-data
        android:name="androidx.glance.wear.widget.provider"
        android:resource="@xml/hello_widget_info" />

    <meta-data
        android:name="androidx.wear.tiles.PREVIEW"
        android:resource="@drawable/tile_preview" />
</service>

빌드 및 배포

서비스와 위젯을 정의한 후 프로젝트를 빌드하고 기기 또는 에뮬레이터에 배포할 수 있습니다.

빌드 및 설치

프로젝트를 빌드하고 연결된 기기 또는 에뮬레이터에 디버그 APK를 설치합니다.

./gradlew :app:installDebug

위젯 추가 및 미리보기

앱이 설치된 후 adb를 사용하여 프로그래매틱 방식으로 위젯을 캐러셀에 추가하고 화면에 표시합니다.

참고: Wear 위젯은 디버깅 목적으로 기본 타일 인프라를 사용합니다. 따라서 adb 명령어에는 add-tileshow-tile 작업이 필요합니다.

1. 캐러셀에 위젯 추가:

adb shell am broadcast \
  -a com.google.android.wearable.app.DEBUG_SURFACE \
  --es operation add-tile \
  --ecn component <your_package_name>/.HelloWidgetService

2. 위젯 표시:

adb shell am broadcast \
  -a com.google.android.wearable.app.DEBUG_SYSUI \
  --es operation show-tile \
  --ei index 0

Android 스튜디오 미리보기를 사용하여 다양한 화면 크기에서 레이아웃을 테스트할 수도 있습니다.