package jp.thb.tracker import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Build import android.os.Bundle import android.os.Handler import android.os.IBinder import android.os.Looper import android.os.PowerManager import androidx.core.app.NotificationCompat import jp.thb.tracker.data.SelfTrack import org.json.JSONArray import org.json.JSONObject import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone import java.util.concurrent.atomic.AtomicBoolean import kotlin.concurrent.thread /** * Reports the phone's own position to the THB server every N hours (1-hour steps). * * A cell/Wi-Fi fix is preferred. If the network provider gives nothing within * 30 s, one GPS fix is requested (up to 90 s), and finally the newest last-known * position is used. Every attempt is stored in SharedPreferences so the * "端末" tab can show the result. */ class SelfTrackService : Service() { companion object { const val ACTION_TICK = "jp.thb.tracker.SELF_TICK" const val ACTION_ONCE = "jp.thb.tracker.SELF_ONCE" const val ACTION_STOP = "jp.thb.tracker.SELF_STOP" private const val CHANNEL = "thb_selftrack" private const val NOTIF_ID = 1001 } private val handler = Handler(Looper.getMainLooper()) private var busy = false private var foreground = false private val tick = object : Runnable { override fun run() { if (!SelfTrack.enabled(this@SelfTrackService)) { stopSelf() return } runWork(once = false) handler.postDelayed(this, SelfTrack.hours(this@SelfTrackService) * 3_600_000L) } } override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { super.onCreate() jp.thb.tracker.net.Tls.install(this) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { ACTION_STOP -> { getSharedPreferences("thb_selftrack", MODE_PRIVATE).edit() .putBoolean("enabled", false).apply() handler.removeCallbacks(tick) stopForegroundCompat() stopSelf() return START_NOT_STICKY } ACTION_ONCE -> { ensureForeground() runWork(once = true) return START_STICKY } else -> { ensureForeground() handler.removeCallbacks(tick) if (!SelfTrack.enabled(this)) { stopForegroundCompat() stopSelf() return START_NOT_STICKY } runWork(once = false) handler.postDelayed(tick, SelfTrack.hours(this) * 3_600_000L) return START_STICKY } } } override fun onDestroy() { handler.removeCallbacks(tick) super.onDestroy() } // ---------------------------------------------------------------- work private fun runWork(once: Boolean) { if (busy) return busy = true updateNotification("位置を取得しています…") val power = getSystemService(Context.POWER_SERVICE) as? PowerManager val wake = power?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "thb:selftrack")?.also { runCatching { it.acquire(4 * 60_000L) } } locate { loc -> if (loc == null) { SelfTrack.noteError(this, "位置を取得できませんでした(この端末は GPS のみ。屋外でお試しください)") finish(wake, once, "位置を取得できませんでした", ok = false) return@locate } thread { val err = post(loc) handler.post { if (err == null) { val acc = if (loc.hasAccuracy()) " 精度 ${loc.accuracy.toInt()}m" else "" SelfTrack.noteOk(this, "送信しました$acc") finish(wake, once, "送信しました$acc", ok = true) } else { SelfTrack.noteError(this, err) finish(wake, once, "送信失敗: $err", ok = false) } } } } } private fun finish(wake: PowerManager.WakeLock?, once: Boolean, message: String, ok: Boolean) { if (wake?.isHeld == true) runCatching { wake.release() } busy = false updateNotification(message) if (once && !SelfTrack.enabled(this)) { handler.postDelayed({ stopForegroundCompat() stopSelf() }, 3_000) } } // ------------------------------------------------------------ location private fun locate(onDone: (Location?) -> Unit) { val lm = getSystemService(Context.LOCATION_SERVICE) as? LocationManager if (lm == null) { onDone(null) return } // This handset's real network provider is Qualcomm IZat, exposed as the // remote "fused" provider (persist.loc.nlp_name=com.qualcomm.location). // getProvider("fused") returns null for apps here, so just try the names // and fall back when the request is rejected. val order = buildList { for (p in listOf( LocationManager.NETWORK_PROVIDER, "fused", "sbm_lib", LocationManager.PASSIVE_PROVIDER, LocationManager.GPS_PROVIDER, )) if (p !in this) add(p) for (p in runCatching { lm.getProviders(true) }.getOrDefault(emptyList())) { if (p !in this) add(p) } } val best = order.mapNotNull { p -> runCatching { lm.getLastKnownLocation(p) }.getOrNull() }.maxByOrNull { it.time } // A recent fix is good enough and costs no radio time. if (best != null && System.currentTimeMillis() - best.time < 10 * 60_000L) { onDone(best) return } fun tryNext(index: Int) { if (index >= order.size) { onDone(best) return } val provider = order[index] val timeout = when (provider) { LocationManager.GPS_PROVIDER -> 90_000L "fused" -> 30_000L // Qualcomm IZat (network) - often unavailable here "sbm_lib" -> 20_000L // SoftBank provider: accepts the request, no fix LocationManager.PASSIVE_PROVIDER -> 5_000L else -> 10_000L } requestOnce(lm, provider, timeout) { loc -> if (loc != null) onDone(loc) else tryNext(index + 1) } } tryNext(0) } private fun requestOnce( lm: LocationManager, provider: String, timeoutMs: Long, onDone: (Location?) -> Unit, ) { // No isProviderEnabled() pre-check: "fused" is a remote provider here and // reports disabled, but requestSingleUpdate() still works. val done = AtomicBoolean(false) var listener: LocationListener? = null val timeout = Runnable { if (done.compareAndSet(false, true)) { listener?.let { l -> runCatching { lm.removeUpdates(l) } } onDone(null) } } val l = object : LocationListener { override fun onLocationChanged(location: Location) { if (done.compareAndSet(false, true)) { runCatching { lm.removeUpdates(this) } handler.removeCallbacks(timeout) onDone(location) } } override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {} } listener = l try { lm.requestSingleUpdate(provider, l, Looper.getMainLooper()) handler.postDelayed(timeout, timeoutMs) } catch (e: Exception) { if (done.compareAndSet(false, true)) onDone(null) } } // ------------------------------------------------------------- network private fun post(loc: Location): String? { val prefs = getSharedPreferences("thb", MODE_PRIVATE) val base = prefs.getString("baseUrl", "").orEmpty().trim().trimEnd('/') val token = prefs.getString("token", "").orEmpty().trim() if (base.isBlank()) return "サーバー URL が未設定です(設定 → サーバー設定)" val point = JSONObject() .put("time", isoTime(loc.time)) .put("lat", loc.latitude) .put("lon", loc.longitude) .put("accuracy_m", if (loc.hasAccuracy()) loc.accuracy.toDouble() else JSONObject.NULL) val body = JSONObject().put("name", "この端末").put("points", JSONArray().put(point)) var conn: HttpURLConnection? = null return try { conn = (URL("$base/api/self/points").openConnection() as HttpURLConnection).apply { requestMethod = "POST" connectTimeout = 10_000 readTimeout = 20_000 doOutput = true setRequestProperty("Content-Type", "application/json; charset=utf-8") if (token.isNotBlank()) setRequestProperty("X-Auth", token) } conn.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) } val code = conn.responseCode val text = (if (code in 200..299) conn.inputStream else conn.errorStream)?.use { input -> BufferedReader(InputStreamReader(input, Charsets.UTF_8)).readText() }.orEmpty() if (code !in 200..299) "HTTP $code ${text.take(120)}" else null } catch (e: Exception) { e.message ?: e.javaClass.simpleName } finally { runCatching { conn?.disconnect() } } } private fun isoTime(millis: Long): String { val f = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US) f.timeZone = TimeZone.getTimeZone("UTC") return f.format(Date(millis)) } // -------------------------------------------------------- notification private fun ensureForeground(text: String = "待機中") { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val nm = getSystemService(NotificationManager::class.java) if (nm != null && nm.getNotificationChannel(CHANNEL) == null) { nm.createNotificationChannel( NotificationChannel(CHANNEL, "この端末の追跡", NotificationManager.IMPORTANCE_LOW) ) } } try { startForeground(NOTIF_ID, buildNotification(text)) foreground = true } catch (e: Exception) { // Android 14 can refuse a location foreground service started from // the background; the periodic work simply will not run there. foreground = false } } private fun updateNotification(text: String) { if (!foreground) return runCatching { val nm = getSystemService(NotificationManager::class.java) nm?.notify(NOTIF_ID, buildNotification(text)) } } private fun buildNotification(text: String): Notification { val flags = PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0 val open = PendingIntent.getActivity( this, 0, Intent(this, MainActivity::class.java), flags ) return NotificationCompat.Builder(this, CHANNEL) .setSmallIcon(android.R.drawable.ic_menu_mylocation) .setContentTitle("この端末を追跡中") .setContentText(text) .setOngoing(true) .setOnlyAlertOnce(true) .setContentIntent(open) .build() } @Suppress("DEPRECATION") private fun stopForegroundCompat() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { stopForeground(STOP_FOREGROUND_REMOVE) } else { stopForeground(true) } foreground = false } }