package `in`.caresoft.carepulse.connect.ble import android.app.Notification import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import `in`.caresoft.carepulse.connect.App import `in`.caresoft.carepulse.connect.R import `in`.caresoft.carepulse.connect.ui.MainActivity /** * "Auto-listen" mode for home kits: keeps scanning in the background so a reading taken any time * reaches the care team without opening the app. Runs as a connectedDevice foreground service. */ class CollectService : Service(), BleCollector.Listener { private var collector: BleCollector? = null override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { ServiceCompat.startForeground(this, 7, note("Listening for your health devices"), if (Build.VERSION.SDK_INT >= 29) ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE else 0) if (collector == null) collector = BleCollector(this, this).also { it.start(timeoutMs = null) } return START_STICKY } override fun onDestroy() { collector?.stop(); collector = null; super.onDestroy() } override fun onStatus(text: String) {} override fun onReadings(deviceName: String, readings: List) { getSystemService(android.app.NotificationManager::class.java).notify(8, note("Sent: ${BleCollector.describe(readings)}")) } private fun note(text: String): Notification = NotificationCompat.Builder(this, App.CH_SERVICE) .setSmallIcon(R.drawable.ic_stat).setContentTitle(getString(R.string.app_name)).setContentText(text).setOngoing(true) .setContentIntent(PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)) .build() companion object { fun start(ctx: Context) = ctx.startForegroundService(Intent(ctx, CollectService::class.java)) fun stop(ctx: Context) = ctx.stopService(Intent(ctx, CollectService::class.java)) } }