Files
GPSTracker_wear/wear/src/main/java/de/tstratmann/gpstracker/GPXManager.kt
T
2026-03-06 08:20:54 +01:00

62 lines
2.0 KiB
Kotlin

package de.tstratmann.gpstracker
import android.content.Context
import android.location.Location
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class GPXManager(private val context: Context) {
private var currentFile: File? = null
fun startNewSession(): File {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val fileName = "track_$timeStamp.gpx"
val file = File(context.filesDir, fileName)
file.writeText(getGpxHeader())
currentFile = file
return file
}
fun appendLocation(location: Location) {
currentFile?.let { file ->
val time = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}.format(Date(location.time))
val trkpt = """
<trkpt lat="${location.latitude}" lon="${location.longitude}">
<ele>${location.altitude}</ele>
<time>$time</time>
</trkpt>
""".trimIndent()
val content = file.readText().removeSuffix(getGpxFooter())
file.writeText(content + trkpt + getGpxFooter())
}
}
fun getActivitiesCount(): Int {
return context.filesDir.listFiles { _, name -> name.endsWith(".gpx") }?.size ?: 0
}
fun getAllFiles(): List<File> {
return context.filesDir.listFiles { _, name -> name.endsWith(".gpx") }?.toList() ?: emptyList()
}
private fun getGpxHeader() = """
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="WearGPSTracker" xmlns="http://www.topografix.com/GPX/1/1">
<trk>
<name>Track ${SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date())}</name>
<trkseg>
""".trimIndent()
private fun getGpxFooter() = """
</trkseg>
</trk>
</gpx>
""".trimIndent()
}