Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / maps / src / main / java / com / vayunmathur / maps / intents / FamilyLocationClient.kt
FamilyLocationClient.kt220 lines · 7.9 KiBRaw
| 1 | package com.vayunmathur.maps.intents |
| 2 | |
| 3 | import android.content.ComponentName |
| 4 | import android.content.Context |
| 5 | import android.content.Intent |
| 6 | import android.content.ServiceConnection |
| 7 | import android.os.Bundle |
| 8 | import android.os.Handler |
| 9 | import android.os.IBinder |
| 10 | import android.os.Looper |
| 11 | import android.os.Message |
| 12 | import android.os.Messenger |
| 13 | import android.os.RemoteException |
| 14 | import androidx.compose.runtime.Composable |
| 15 | import androidx.compose.runtime.DisposableEffect |
| 16 | import androidx.compose.runtime.State |
| 17 | import androidx.compose.runtime.mutableStateOf |
| 18 | import androidx.compose.runtime.remember |
| 19 | import androidx.compose.ui.platform.LocalContext |
| 20 | |
| 21 | /** |
| 22 | * Client for findfamily's live family-location channel (see |
| 23 | * [FamilyLocationProtocol]). Binds the remote [Messenger] service, registers a |
| 24 | * reply Messenger, and delivers each pushed snapshot to [onUpdate] on the main |
| 25 | * thread. |
| 26 | * |
| 27 | * Absence handling is total: if findfamily isn't installed, the service can't be |
| 28 | * resolved, the permission is denied, or binding otherwise fails, [bind] simply |
| 29 | * no-ops and no members are ever delivered — the feature is absent with no crash. |
| 30 | */ |
| 31 | class FamilyLocationClient( |
| 32 | context: Context, |
| 33 | private val onUpdate: (List<FamilyMember>) -> Unit, |
| 34 | ) { |
| 35 | private val appContext = context.applicationContext |
| 36 | |
| 37 | private val incoming = Messenger( |
| 38 | Handler(Looper.getMainLooper()) { msg -> |
| 39 | if (msg.what == FamilyLocationProtocol.MSG_LOCATIONS) { |
| 40 | onUpdate(parseSnapshot(msg.data)) |
| 41 | true |
| 42 | } else { |
| 43 | false |
| 44 | } |
| 45 | } |
| 46 | ) |
| 47 | |
| 48 | private var service: Messenger? = null |
| 49 | private var bound = false |
| 50 | |
| 51 | private val connection = object : ServiceConnection { |
| 52 | override fun onServiceConnected(name: ComponentName?, binder: IBinder?) { |
| 53 | val remote = Messenger(binder) |
| 54 | service = remote |
| 55 | try { |
| 56 | val msg = Message.obtain(null, FamilyLocationProtocol.MSG_REGISTER) |
| 57 | msg.replyTo = incoming |
| 58 | remote.send(msg) |
| 59 | } catch (_: RemoteException) { |
| 60 | // Service died between connect and register — nothing to stream. |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | override fun onServiceDisconnected(name: ComponentName?) { |
| 65 | service = null |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /** Resolve + bind the findfamily service. Safe to call once per lifecycle. */ |
| 70 | fun bind() { |
| 71 | if (bound) return |
| 72 | val intent = resolveServiceIntent() ?: return |
| 73 | bound = try { |
| 74 | appContext.bindService(intent, connection, Context.BIND_AUTO_CREATE) |
| 75 | } catch (_: SecurityException) { |
| 76 | // Permission not granted (not co-signed / not held) — feature absent. |
| 77 | false |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /** Unregister and unbind. Idempotent; safe even if [bind] never connected. */ |
| 82 | fun unbind() { |
| 83 | if (!bound) return |
| 84 | try { |
| 85 | val msg = Message.obtain(null, FamilyLocationProtocol.MSG_UNREGISTER) |
| 86 | msg.replyTo = incoming |
| 87 | service?.send(msg) |
| 88 | } catch (_: RemoteException) { |
| 89 | // Already gone — the service tears its own stream down on death. |
| 90 | } |
| 91 | try { |
| 92 | appContext.unbindService(connection) |
| 93 | } catch (_: IllegalArgumentException) { |
| 94 | // Not actually bound (e.g. connection never established). |
| 95 | } |
| 96 | bound = false |
| 97 | service = null |
| 98 | } |
| 99 | |
| 100 | /** |
| 101 | * Build an explicit intent for the findfamily service by resolving the |
| 102 | * declared [FamilyLocationProtocol.ACTION]. Resolving (rather than |
| 103 | * hard-coding a component) tolerates any applicationId suffix and returns |
| 104 | * null when findfamily isn't installed, so the caller degrades to "absent". |
| 105 | */ |
| 106 | private fun resolveServiceIntent(): Intent? { |
| 107 | val intent = Intent(FamilyLocationProtocol.ACTION) |
| 108 | val resolved = appContext.packageManager |
| 109 | .queryIntentServices(intent, 0) |
| 110 | .firstOrNull() |
| 111 | ?.serviceInfo |
| 112 | ?: return null |
| 113 | intent.component = ComponentName(resolved.packageName, resolved.name) |
| 114 | return intent |
| 115 | } |
| 116 | |
| 117 | private fun parseSnapshot(data: Bundle?): List<FamilyMember> { |
| 118 | val arrays = snapshotArrays(data) ?: return emptyList() |
| 119 | // Guard against a malformed / mismatched payload rather than trusting the |
| 120 | // arrays line up — take the length they all agree on. |
| 121 | val count = minOf( |
| 122 | arrays.ids.size, |
| 123 | arrays.names.size, |
| 124 | arrays.lats.size, |
| 125 | arrays.lngs.size, |
| 126 | arrays.timestamps.size, |
| 127 | ) |
| 128 | val out = ArrayList<FamilyMember>(count) |
| 129 | for (i in 0 until count) { |
| 130 | out.add( |
| 131 | FamilyMember( |
| 132 | id = arrays.ids[i], |
| 133 | name = arrays.names[i], |
| 134 | lat = arrays.lats[i], |
| 135 | lng = arrays.lngs[i], |
| 136 | timestamp = arrays.timestamps[i], |
| 137 | battery = arrays.batteries?.getOrNull(i) ?: NO_BATTERY, |
| 138 | ) |
| 139 | ) |
| 140 | } |
| 141 | return out |
| 142 | } |
| 143 | |
| 144 | private fun snapshotArrays(data: Bundle?): SnapshotArrays? { |
| 145 | if (data == null) return null |
| 146 | val required = requiredArrays(data) ?: return null |
| 147 | return SnapshotArrays( |
| 148 | ids = required.ids, |
| 149 | names = required.names, |
| 150 | lats = required.lats, |
| 151 | lngs = required.lngs, |
| 152 | timestamps = required.timestamps, |
| 153 | batteries = data.getFloatArray(FamilyLocationProtocol.KEY_BATTERIES), |
| 154 | ) |
| 155 | } |
| 156 | |
| 157 | /** The five parallel arrays a snapshot needs; null when any is missing. */ |
| 158 | private fun requiredArrays(data: Bundle): RequiredArrays? { |
| 159 | val ids = data.getLongArray(FamilyLocationProtocol.KEY_IDS) ?: return null |
| 160 | val names = data.getStringArray(FamilyLocationProtocol.KEY_NAMES) ?: return null |
| 161 | val lats = data.getDoubleArray(FamilyLocationProtocol.KEY_LATS) ?: return null |
| 162 | val lngs = data.getDoubleArray(FamilyLocationProtocol.KEY_LNGS) ?: return null |
| 163 | val timestamps = data.getLongArray(FamilyLocationProtocol.KEY_TIMESTAMPS) ?: return null |
| 164 | return RequiredArrays(ids, names, lats, lngs, timestamps) |
| 165 | } |
| 166 | |
| 167 | private data class RequiredArrays( |
| 168 | val ids: LongArray, |
| 169 | val names: Array<String>, |
| 170 | val lats: DoubleArray, |
| 171 | val lngs: DoubleArray, |
| 172 | val timestamps: LongArray, |
| 173 | ) { |
| 174 | override fun equals(other: Any?): Boolean = super.equals(other) |
| 175 | override fun hashCode(): Int = super.hashCode() |
| 176 | } |
| 177 | |
| 178 | private data class SnapshotArrays( |
| 179 | val ids: LongArray, |
| 180 | val names: Array<String>, |
| 181 | val lats: DoubleArray, |
| 182 | val lngs: DoubleArray, |
| 183 | val timestamps: LongArray, |
| 184 | val batteries: FloatArray?, |
| 185 | ) { |
| 186 | override fun equals(other: Any?): Boolean = super.equals(other) |
| 187 | override fun hashCode(): Int = super.hashCode() |
| 188 | } |
| 189 | |
| 190 | /** Shared constants and helpers for FamilyLocationClient. */ |
| 191 | companion object { |
| 192 | /** Battery sentinel when the payload carries no battery array. */ |
| 193 | private const val NO_BATTERY = -1f |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * Bind the findfamily family-location channel for exactly as long as the calling |
| 199 | * composable is in the composition, returning the latest pushed members as |
| 200 | * Compose state. |
| 201 | * |
| 202 | * Tied to the map screen's lifecycle via [DisposableEffect]: it binds when the |
| 203 | * screen opens and unbinds when it closes, so findfamily only does the streaming |
| 204 | * work while maps is actually showing the map. If findfamily is absent the state |
| 205 | * simply stays empty. |
| 206 | */ |
| 207 | @Composable |
| 208 | fun rememberFamilyMembers(): State<List<FamilyMember>> { |
| 209 | val context = LocalContext.current |
| 210 | val members = remember { mutableStateOf<List<FamilyMember>>(emptyList()) } |
| 211 | DisposableEffect(Unit) { |
| 212 | val client = FamilyLocationClient(context) { members.value = it } |
| 213 | client.bind() |
| 214 | onDispose { |
| 215 | client.unbind() |
| 216 | members.value = emptyList() |
| 217 | } |
| 218 | } |
| 219 | return members |
| 220 | } |