Files
MicrOBU/app/src/main/java/com/hawhamburg/micr0bu/service/V2xLogService.kt
T

136 lines
4.8 KiB
Kotlin
Raw Normal View History

package com.hawhamburg.micr0bu.service
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.content.pm.ServiceInfo
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.hawhamburg.micr0bu.MainActivity
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.log.V2xLogger
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
/**
* Keeps the process alive, and the CPU awake, while [V2xLogger] records.
*
* The logger does the work; this exists only because a log is most useful on a drive, with the
* screen off, and a process with no foreground service is one the system may kill and whose GNSS
* callbacks it throttles. Same shape as [TripRecordingService], which does this for trips.
*
* Stops itself when the logger stops, including when the logger stops on a write failure.
*/
@AndroidEntryPoint
class V2xLogService : Service() {
@Inject lateinit var logger: V2xLogger
private val job = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.Default + job)
private var watchJob: Job? = null
private var wakeLock: PowerManager.WakeLock? = null
override fun onCreate() {
super.onCreate()
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
NotificationChannel(CHANNEL_ID, "V2X logging", NotificationManager.IMPORTANCE_LOW).apply {
description = "Shown while the developer V2X data logger is recording"
}
)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_START -> begin()
ACTION_STOP -> end()
}
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
wakeLock?.let { if (it.isHeld) it.release() }
job.cancel()
super.onDestroy()
}
private fun begin() {
// Foreground first: Android allows five seconds from startForegroundService.
startForeground(NOTIFICATION_ID, notification(0), ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)
wakeLock = (getSystemService(POWER_SERVICE) as PowerManager)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "micr0bu:V2xLog")
.also { it.acquire() }
logger.start()
if (!logger.state.value.active) { // the file could not be created; the screen shows why
end()
return
}
watchJob?.cancel()
watchJob = scope.launch {
logger.state.collect { state ->
if (!state.active) {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
} else {
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
.notify(NOTIFICATION_ID, notification(state.total))
}
}
}
}
private fun end() {
scope.launch {
logger.stop()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
private fun notification(messages: Int) =
NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Logging V2X messages")
.setContentText("$messages messages recorded")
.setSmallIcon(R.mipmap.ic_launcher_foreground)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setContentIntent(
PendingIntent.getActivity(
this, 0,
Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
},
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
)
.build()
companion object {
const val ACTION_START = "com.hawhamburg.micr0bu.V2X_LOG_START"
const val ACTION_STOP = "com.hawhamburg.micr0bu.V2X_LOG_STOP"
private const val NOTIFICATION_ID = 9002
private const val CHANNEL_ID = "v2x_logging"
fun start(context: Context) = ContextCompat.startForegroundService(
context, Intent(context, V2xLogService::class.java).setAction(ACTION_START)
)
fun stop(context: Context) {
context.startService(Intent(context, V2xLogService::class.java).setAction(ACTION_STOP))
}
}
}