fix: 워치가 옮겨 간 위치를 따라 날씨·각·축제를 받도록

- 요약을 받을 때마다 지금 위치의 구를 다시 찾는다 (전엔 처음 찾은 구로 고정)
- 마지막 위치가 비어 있는 시계가 많아 지금 위치를 5초 안에 한 번 묻고, 못 얻으면 마지막 위치 → 저장된 구 순서

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 5.5 committed 2026-10-07 14:04:01 +09:00
1 parent b4d028a91b
commit e4d9640e1f
1 file changed
+23 -2
@@ -4,8 +4,11 @@ import android.Manifest
import android.content.ComponentName import android.content.ComponentName
import android.content.Context import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager import android.location.LocationManager
import android.os.CancellationSignal
import android.util.Log import android.util.Log
import androidx.annotation.RequiresPermission
import androidx.wear.tiles.TileService import androidx.wear.tiles.TileService
import androidx.wear.watchface.complications.datasource.ComplicationDataSourceUpdateRequester import androidx.wear.watchface.complications.datasource.ComplicationDataSourceUpdateRequester
import org.json.JSONArray import org.json.JSONArray
@@ -17,6 +20,8 @@ import java.time.Instant
import java.time.OffsetDateTime import java.time.OffsetDateTime
import java.time.ZoneId import java.time.ZoneId
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
data class Gak(val code: String, val name: String, val icon: String, val score: Int, val rank: Int, val summary: String?) data class Gak(val code: String, val name: String, val icon: String, val score: Int, val rank: Int, val summary: String?)
data class Sunset(val isToday: Boolean, val score: Int, val grade: String, val sunsetAt: Instant, val bestAt: Instant) data class Sunset(val isToday: Boolean, val score: Int, val grade: String, val sunsetAt: Instant, val bestAt: Instant)
@@ -108,6 +113,7 @@ object SummaryRepo {
private const val PICKS = "running,laundry,walk" private const val PICKS = "running,laundry,walk"
// 위치를 못 얻으면 종로구 // 위치를 못 얻으면 종로구
private const val DEFAULT_REGION = "1111000000" private const val DEFAULT_REGION = "1111000000"
private const val LOCATION_TIMEOUT_SEC = 5L
/** 캐시가 refresh_at 전이면 캐시, 아니면 새로 받는다. 받기 실패하면 지난 캐시라도. 네트워크를 쓰니 메인 스레드에서 부르지 않는다. */ /** 캐시가 refresh_at 전이면 캐시, 아니면 새로 받는다. 받기 실패하면 지난 캐시라도. 네트워크를 쓰니 메인 스레드에서 부르지 않는다. */
fun load(context: Context, force: Boolean = false): Summary? = fetch(context, force)?.let { s -> fun load(context: Context, force: Boolean = false): Summary? = fetch(context, force)?.let { s ->
@@ -121,7 +127,8 @@ object SummaryRepo {
val cached = prefs.getString("json", null)?.let { runCatching { parseSummary(it) }.getOrNull() } val cached = prefs.getString("json", null)?.let { runCatching { parseSummary(it) }.getOrNull() }
if (!force && cached != null && Instant.now() < cached.refreshAt) return cached if (!force && cached != null && Instant.now() < cached.refreshAt) return cached
return try { return try {
val region = prefs.getString("region", null) ?: nearestRegion(context)?.also { prefs.edit().putString("region", it).apply() } ?: DEFAULT_REGION // 받을 때마다 지금 위치의 구를 다시 찾아, 옮겨 가면 날씨·각·축제가 따라온다. 위치를 못 얻으면 지난 구
val region = nearestRegion(context)?.also { prefs.edit().putString("region", it).apply() } ?: prefs.getString("region", null) ?: DEFAULT_REGION
val json = get("/v1/watch/summary?region=$region&pick=$PICKS") val json = get("/v1/watch/summary?region=$region&pick=$PICKS")
val fresh = parseSummary(json) val fresh = parseSummary(json)
prefs.edit().putString("json", json).apply() prefs.edit().putString("json", json).apply()
@@ -146,7 +153,8 @@ object SummaryRepo {
private fun nearestRegion(context: Context): String? { private fun nearestRegion(context: Context): String? {
if (context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) return null if (context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) return null
val lm = context.getSystemService(LocationManager::class.java) val lm = context.getSystemService(LocationManager::class.java)
val loc = lm.getProviders(true).firstNotNullOfOrNull { lm.getLastKnownLocation(it) } ?: return null // 다른 앱이 위치를 갱신하지 않았으면 마지막 위치가 비어 있어, 먼저 지금 위치를 한 번 묻는다
val loc = currentLocation(lm) ?: lm.getProviders(true).firstNotNullOfOrNull { lm.getLastKnownLocation(it) } ?: return null
return try { return try {
JSONObject(get("/v1/region/nearest?lat=${loc.latitude}&lon=${loc.longitude}")).getJSONObject("region").getString("code") JSONObject(get("/v1/region/nearest?lat=${loc.latitude}&lon=${loc.longitude}")).getJSONObject("region").getString("code")
} catch (e: IOException) { } catch (e: IOException) {
@@ -156,6 +164,19 @@ object SummaryRepo {
} }
} }
/** 지금 위치 한 번. 구 단위면 되니 대략 위치, 5초 안에 못 얻으면 null (백그라운드에선 시스템이 자주 거절한다) */
@RequiresPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
private fun currentLocation(lm: LocationManager): Location? {
val enabled = lm.getProviders(true)
val provider = listOf("fused", LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER).firstOrNull { it in enabled } ?: return null
val done = CountDownLatch(1)
val cancel = CancellationSignal()
var loc: Location? = null
lm.getCurrentLocation(provider, cancel, { it.run() }) { loc = it; done.countDown() }
if (!done.await(LOCATION_TIMEOUT_SEC, TimeUnit.SECONDS)) cancel.cancel()
return loc
}
private fun get(path: String): String { private fun get(path: String): String {
val conn = URL(BuildConfig.API_BASE + path).openConnection() as HttpURLConnection val conn = URL(BuildConfig.API_BASE + path).openConnection() as HttpURLConnection
conn.connectTimeout = 5000 conn.connectTimeout = 5000