Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / networklocation / src / main / java / com / vayunmathur / networklocation / ui / LiveLocationSection.kt

LiveLocationSection.kt182 lines · 7.5 KiBRaw
1package com.vayunmathur.networklocation.ui
2
3import android.content.Context
4import android.location.Address
5import android.location.Location
6import android.location.LocationManager
7import android.os.SystemClock
8import androidx.compose.foundation.layout.Column
9import androidx.compose.foundation.layout.fillMaxWidth
10import androidx.compose.foundation.layout.padding
11import androidx.compose.runtime.Composable
12import androidx.compose.runtime.LaunchedEffect
13import androidx.compose.runtime.collectAsState
14import androidx.compose.runtime.getValue
15import androidx.compose.runtime.mutableLongStateOf
16import androidx.compose.runtime.mutableStateOf
17import androidx.compose.runtime.remember
18import androidx.compose.runtime.setValue
19import androidx.compose.ui.Modifier
20import androidx.compose.ui.platform.LocalContext
21import androidx.compose.ui.unit.dp
22import com.vayunmathur.library.ui.Card
23import com.vayunmathur.library.ui.MaterialTheme
24import com.vayunmathur.library.ui.Text
25import com.vayunmathur.networklocation.platform.hasFineLocation
26import com.vayunmathur.networklocation.platform.locationUpdates
27import com.vayunmathur.networklocation.platform.reverseGeocode
28import kotlinx.coroutines.delay
29import java.util.Locale
30
31/** Re-geocode only after the GPS fix has moved this far, not on every one-second fix. */
32private const val REGEOCODE_DISTANCE_M = 25f
33private const val NANOS_PER_SECOND = 1_000_000_000L
34private const val TICK_MS = 1_000L
35
36private sealed interface GeocodeState {
37 data object WaitingForGps : GeocodeState
38 data object Looking : GeocodeState
39 data class Found(val address: Address, val from: Location) : GeocodeState
40 data object NoMatch : GeocodeState
41 data class Failed(val message: String) : GeocodeState
42}
43
44/**
45 * Live check of both halves of the app: the GPS fix, this app's own network-location fix, and
46 * the GPS fix run through the offline geocoder. GPS rather than the network fix is geocoded so
47 * the geocoder is judged against a position that does not depend on the beacon stores.
48 */
49@Composable
50fun LiveLocationSection(
51 modifier: Modifier = Modifier,
52 // Injectable so tests can drive the Found/Failed states without a geocoder backend;
53 // production always uses the system Geocoder through this app's own GeocodeService.
54 geocodeLookup: suspend (Context, Double, Double) -> Result<Address?> =
55 { context, lat, lon -> reverseGeocode(context, lat, lon) },
56) {
57 val context = LocalContext.current
58 if (!hasFineLocation(context)) {
59 Text(
60 "Location permission is not granted, so live positions cannot be shown.",
61 modifier = modifier,
62 style = MaterialTheme.typography.bodyMedium,
63 )
64 return
65 }
66
67 val gpsFlow = remember { locationUpdates(context, LocationManager.GPS_PROVIDER) }
68 val networkFlow = remember { locationUpdates(context, LocationManager.NETWORK_PROVIDER) }
69 val gps by gpsFlow.collectAsState(initial = null)
70 val network by networkFlow.collectAsState(initial = null)
71
72 // Fix ages are shown live, so recompose once a second.
73 var now by remember { mutableLongStateOf(SystemClock.elapsedRealtimeNanos()) }
74 LaunchedEffect(Unit) {
75 while (true) {
76 delay(TICK_MS)
77 now = SystemClock.elapsedRealtimeNanos()
78 }
79 }
80
81 var anchor by remember { mutableStateOf<Location?>(null) }
82 LaunchedEffect(gps) {
83 val fix = gps ?: return@LaunchedEffect
84 if (anchor?.let { it.distanceTo(fix) > REGEOCODE_DISTANCE_M } != false) anchor = fix
85 }
86 var geocode by remember { mutableStateOf<GeocodeState>(GeocodeState.WaitingForGps) }
87 LaunchedEffect(anchor) {
88 val fix = anchor ?: return@LaunchedEffect
89 geocode = GeocodeState.Looking
90 geocode = geocodeLookup(context, fix.latitude, fix.longitude).fold(
91 onSuccess = { a -> a?.let { GeocodeState.Found(it, fix) } ?: GeocodeState.NoMatch },
92 onFailure = { GeocodeState.Failed(it.message ?: it.javaClass.simpleName) },
93 )
94 }
95
96 Column(modifier) {
97 Text("Live check", style = MaterialTheme.typography.titleMedium)
98 FixCard("GPS", gps, now, emptyText = "Waiting for a GPS fix… (go outside or near a window)")
99 FixCard(
100 "Network location (this app)",
101 network,
102 now,
103 emptyText = "No network fix yet. Cell and Wi-Fi scans resolve against the offline stores.",
104 comparedTo = gps,
105 )
106 GeocodeCard(geocode)
107 }
108}
109
110@Composable
111private fun FixCard(
112 title: String,
113 fix: Location?,
114 now: Long,
115 emptyText: String,
116 comparedTo: Location? = null,
117) {
118 Card(Modifier.fillMaxWidth().padding(top = 12.dp)) {
119 Column(Modifier.padding(16.dp)) {
120 Text(title, style = MaterialTheme.typography.titleSmall)
121 if (fix == null) {
122 Text(emptyText, Modifier.padding(top = 4.dp), style = MaterialTheme.typography.bodyMedium)
123 return@Column
124 }
125 Text(
126 coords(fix.latitude, fix.longitude),
127 Modifier.padding(top = 4.dp),
128 style = MaterialTheme.typography.bodyLarge,
129 )
130 val details = buildList {
131 if (fix.hasAccuracy()) add("±%.0f m".format(Locale.US, fix.accuracy))
132 add("${(now - fix.elapsedRealtimeNanos).coerceAtLeast(0) / NANOS_PER_SECOND} s ago")
133 comparedTo?.let { add("%.0f m from GPS".format(Locale.US, it.distanceTo(fix))) }
134 }
135 Text(details.joinToString(" · "), style = MaterialTheme.typography.bodySmall)
136 }
137 }
138}
139
140@Composable
141private fun GeocodeCard(state: GeocodeState) {
142 Card(Modifier.fillMaxWidth().padding(top = 12.dp)) {
143 Column(Modifier.padding(16.dp)) {
144 Text("Offline geocoder (GPS position)", style = MaterialTheme.typography.titleSmall)
145 val body = Modifier.padding(top = 4.dp)
146 when (state) {
147 GeocodeState.WaitingForGps ->
148 Text("Waiting for a GPS fix to look up.", body, style = MaterialTheme.typography.bodyMedium)
149 GeocodeState.Looking -> Text(
150 "Looking up… the first lookup after the service starts can take a while " +
151 "while the database opens.",
152 body,
153 style = MaterialTheme.typography.bodyMedium,
154 )
155 GeocodeState.NoMatch ->
156 Text("No nearby record in the database.", body, style = MaterialTheme.typography.bodyMedium)
157 is GeocodeState.Failed ->
158 Text("Lookup failed: ${state.message}", body, style = MaterialTheme.typography.bodyMedium)
159 is GeocodeState.Found -> FoundAddress(state.address, state.from)
160 }
161 }
162 }
163}
164
165@Composable
166private fun FoundAddress(a: Address, from: Location) {
167 Text(
168 a.getAddressLine(0) ?: a.featureName ?: "(unnamed)",
169 Modifier.padding(top = 4.dp),
170 style = MaterialTheme.typography.bodyLarge,
171 )
172 val parts = listOfNotNull(a.thoroughfare, a.locality, a.adminArea, a.postalCode, a.countryCode)
173 if (parts.isNotEmpty()) Text(parts.joinToString(", "), style = MaterialTheme.typography.bodyMedium)
174 val match = FloatArray(1)
175 Location.distanceBetween(from.latitude, from.longitude, a.latitude, a.longitude, match)
176 Text(
177 "Record at ${coords(a.latitude, a.longitude)} · %.0f m from the GPS fix".format(Locale.US, match[0]),
178 style = MaterialTheme.typography.bodySmall,
179 )
180}
181
182private fun coords(lat: Double, lon: Double) = "%.6f, %.6f".format(Locale.US, lat, lon)