feat: 워치 페이스 푸시로 앱 설치 때 날씨각 스킨 같이 적용(Wear OS 6+), 앱 첫 장을 오늘 남은 시간→주변 축제 순으로
Play 스토어 심사에 낸 1(0.1) 빌드와 같은 코드 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ee46a101db
commit
e270261e32
9 files changed
+203
-87
No files matched your search
@@ -4,6 +4,9 @@
|
||||
<uses-feature android:name="android.hardware.type.watch" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<!-- 앱과 같이 깔리는 날씨각 스킨을 시계 화면으로 바꾸는 권한 (Watch Face Push) -->
|
||||
<uses-permission android:name="com.google.wear.permission.PUSH_WATCH_FACES" />
|
||||
<uses-permission android:name="com.google.wear.permission.SET_PUSHED_WATCH_FACE_AS_ACTIVE" />
|
||||
|
||||
<application
|
||||
android:icon="@drawable/ic_gak"
|
||||
@@ -13,6 +16,11 @@
|
||||
<!-- 폰 앱 없이 워치에서 단독으로 동작 -->
|
||||
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
|
||||
|
||||
<!-- 앱 설치 때 assets/default_watchface.apk(스킨)도 같이 설치된다. 토큰은 빌드가 만든다 (build.gradle.kts) -->
|
||||
<meta-data
|
||||
android:name="com.google.android.wearable.marketplace.DEFAULT_WATCHFACE_VALIDATION_TOKEN"
|
||||
android:value="@string/default_wf_token" />
|
||||
|
||||
<activity android:name=".MainActivity" android:exported="true" android:taskAffinity="">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -126,7 +134,7 @@
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
<!-- 워치 스킨 숨은 칸용: 비·눈 여부 -->
|
||||
<!-- 워치 스킨 숨은 칸용: 날씨(비·눈·천둥)·기온·가운데 1위 -->
|
||||
<service
|
||||
android:name=".RainComplicationService"
|
||||
android:exported="true"
|
||||
@@ -136,7 +144,7 @@
|
||||
<intent-filter>
|
||||
<action android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="SHORT_TEXT" />
|
||||
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="RANGED_VALUE" />
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package kr.o2o.nalssigak
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -16,29 +18,85 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.wear.compose.foundation.pager.VerticalPager
|
||||
import androidx.wear.compose.foundation.pager.rememberPagerState
|
||||
import androidx.wear.compose.material3.MaterialTheme
|
||||
import androidx.wear.compose.material3.VerticalPageIndicator
|
||||
import androidx.wear.watchfacepush.WatchFacePushManager
|
||||
import androidx.wear.watchfacepush.WatchFacePushManagerFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
/** 컴플리케이션 탭이 실어 보내는 각 코드 */
|
||||
const val EXTRA_GAK = "gak"
|
||||
|
||||
/** 앱과 같이 깔린 스킨을 시계 화면으로 바꾸는 권한. 사용자가 한 번 거절하면 다시 묻지 못한다 */
|
||||
private const val SET_SKIN = "com.google.wear.permission.SET_PUSHED_WATCH_FACE_AS_ACTIVE"
|
||||
private const val TAG = "MainActivity"
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private var summary by mutableStateOf<Summary?>(null)
|
||||
private var loading by mutableStateOf(true)
|
||||
|
||||
private val askLocation = registerForActivityResult(ActivityResultContracts.RequestPermission()) { load() }
|
||||
private val askPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
load()
|
||||
useSkin()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val opened = intent.getStringExtra(EXTRA_GAK)
|
||||
setContent { MaterialTheme { App(summary, loading, opened) { load(force = true) } } }
|
||||
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) load()
|
||||
else askLocation.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
// 위치와 스킨 적용을 한 번에 묻는다
|
||||
val missing = listOf(Manifest.permission.ACCESS_COARSE_LOCATION, SET_SKIN).filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (missing.isEmpty()) {
|
||||
load()
|
||||
useSkin()
|
||||
} else askPermissions.launch(missing.toTypedArray())
|
||||
}
|
||||
|
||||
/**
|
||||
* 앱 설치 때 같이 깔린 날씨각 스킨을 챙긴다.
|
||||
* 앱 업데이트로 새 스킨이 실려 왔으면 바꿔 끼우고(기본 스킨은 처음 설치 때만 깔린다), 허락받았으면 시계 화면으로 바꾼다(시스템이 앱마다 한 번만 허락한다).
|
||||
*/
|
||||
private fun useSkin() {
|
||||
lifecycleScope.launch {
|
||||
val push = WatchFacePushManagerFactory.createWatchFacePushManager(this@MainActivity)
|
||||
try {
|
||||
// 기본 스킨 설치가 아직 안 끝났으면 다음 실행 때 다시 본다
|
||||
val skin = push.listWatchFaces().installedWatchFaceDetails.firstOrNull() ?: return@launch
|
||||
if (skin.versionCode < BuildConfig.SKIN_VERSION) updateSkin(push, skin.slotId)
|
||||
if (checkSelfPermission(SET_SKIN) == PackageManager.PERMISSION_GRANTED && !push.isWatchFaceActive(skin.packageName)) {
|
||||
push.setWatchFaceAsActive(skin.slotId)
|
||||
}
|
||||
} catch (e: WatchFacePushManager.ListWatchFacesException) {
|
||||
Log.w(TAG, "스킨 목록을 못 읽음", e)
|
||||
} catch (e: WatchFacePushManager.UpdateWatchFaceException) {
|
||||
Log.w(TAG, "스킨을 새 버전으로 못 바꿈", e)
|
||||
} catch (e: WatchFacePushManager.IsWatchFaceActiveException) {
|
||||
Log.w(TAG, "스킨 사용 여부를 못 읽음", e)
|
||||
} catch (e: WatchFacePushManager.SetWatchFaceAsActiveException) {
|
||||
// 이미 한 번 바꾼 뒤 사용자가 다른 화면으로 옮긴 경우. 다시 바꾸지 않는다
|
||||
Log.i(TAG, "스킨을 시계 화면으로 바꾸지 않음", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 앱에 실은 스킨(assets/default_watchface.apk)으로 바꿔 끼운다. 검증 토큰은 빌드가 만든 것 (build.gradle.kts) */
|
||||
private suspend fun updateSkin(push: WatchFacePushManager, slotId: String) {
|
||||
val apk = File(cacheDir, "skin.apk")
|
||||
try {
|
||||
withContext(Dispatchers.IO) { assets.open("default_watchface.apk").use { input -> apk.outputStream().use { input.copyTo(it) } } }
|
||||
ParcelFileDescriptor.open(apk, ParcelFileDescriptor.MODE_READ_ONLY).use { push.updateWatchFace(slotId, it, getString(R.string.default_wf_token)) }
|
||||
} finally {
|
||||
apk.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun load(force: Boolean = false) {
|
||||
@@ -50,7 +108,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class Page { DETAIL, EVENTS, TOP, PICKS, SUNSET, HOURS }
|
||||
private enum class Page { DETAIL, HOURS, EVENTS, TOP, PICKS, SUNSET }
|
||||
|
||||
@Composable
|
||||
private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> Unit) {
|
||||
@@ -65,15 +123,15 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U
|
||||
StatePage(loading, onRetry)
|
||||
return
|
||||
}
|
||||
// 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 주변 축제부터 (축제가 없으면 오늘의 각부터)
|
||||
// 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 오늘 남은 시간 → 주변 축제 → 각 순서
|
||||
val detail = opened?.let { c -> (s.top + s.picks).firstOrNull { it.code == c } }
|
||||
val pages = buildList {
|
||||
if (detail != null) add(Page.DETAIL)
|
||||
if (s.slots.isNotEmpty()) add(Page.HOURS)
|
||||
if (s.events.isNotEmpty()) add(Page.EVENTS)
|
||||
if (s.top.isNotEmpty()) add(Page.TOP)
|
||||
if (s.picks.isNotEmpty()) add(Page.PICKS)
|
||||
if (s.sunset != null) add(Page.SUNSET)
|
||||
if (s.slots.isNotEmpty()) add(Page.HOURS)
|
||||
}
|
||||
val state = rememberPagerState { pages.size }
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
|
||||
@@ -1,27 +1,45 @@
|
||||
package kr.o2o.nalssigak
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import androidx.wear.watchface.complications.data.ComplicationData
|
||||
import androidx.wear.watchface.complications.data.ComplicationType
|
||||
import androidx.wear.watchface.complications.data.PlainComplicationText
|
||||
import androidx.wear.watchface.complications.data.ShortTextComplicationData
|
||||
import androidx.wear.watchface.complications.data.RangedValueComplicationData
|
||||
import androidx.wear.watchface.complications.datasource.ComplicationRequest
|
||||
import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"천둥 쳐요"·"눈 와요")을 보고 빗줄기·눈송이와 가운데 구름도 그린다. */
|
||||
/**
|
||||
* 워치 스킨 날씨 칸 + 가운데 1위. 스킨 칸이 8개까지라 한 칸에 몰아 준다.
|
||||
* 값 = 날씨 코드(0 맑음·1 비·2 천둥·3 눈) × 1000 + 1위 점수, 글자 = 지금 기온, 제목 = 1위 이름(없으면 빈 글자).
|
||||
*/
|
||||
class RainComplicationService : SuspendingComplicationDataSourceService() {
|
||||
|
||||
override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? {
|
||||
val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@RainComplicationService) } ?: return null
|
||||
return data(s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", s.rainLabel)
|
||||
val code = when (s.rainLabel) {
|
||||
"비 와요", "곧 비" -> 1
|
||||
"천둥 쳐요" -> 2
|
||||
"눈 와요" -> 3
|
||||
else -> 0
|
||||
}
|
||||
val top = s.top.firstOrNull()
|
||||
return data(code, top?.score ?: 0, s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", top?.name ?: "")
|
||||
}
|
||||
|
||||
override fun getPreviewData(type: ComplicationType): ComplicationData = data("20°", "비 없음")
|
||||
override fun getPreviewData(type: ComplicationType): ComplicationData = data(0, 88, "20°", "산책각")
|
||||
|
||||
private fun data(temp: String, rain: String) = ShortTextComplicationData.Builder(
|
||||
PlainComplicationText.Builder(temp).build(),
|
||||
PlainComplicationText.Builder("$temp $rain").build(),
|
||||
).setTitle(PlainComplicationText.Builder(rain).build()).build()
|
||||
private fun data(code: Int, score: Int, temp: String, name: String): ComplicationData {
|
||||
// 가운데 구슬을 누르면 앱 첫 장
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return RangedValueComplicationData.Builder(code * 1000f + score, 0f, 3100f, PlainComplicationText.Builder("$name $score, $temp").build())
|
||||
.setText(PlainComplicationText.Builder(temp).build())
|
||||
.setTitle(PlainComplicationText.Builder(name).build())
|
||||
.setTapAction(open)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ data class Summary(
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** 스킨 칩의 비 소식. 스킨은 이 글자를 보고 가운데를 비구름·천둥 구름·눈구름으로 바꾼다 */
|
||||
/** 비 소식. 스킨 날씨 칸(RainComplicationService)이 이 글자로 날씨 코드를 정한다 */
|
||||
val rainLabel: String get() = when {
|
||||
precip == "snow" -> "눈 와요"
|
||||
thunder == true -> "천둥 쳐요"
|
||||
|
||||
Reference in new issue
Block a user