automatically record trip id
This commit is contained in:
@@ -16,4 +16,10 @@ interface LocationDao {
|
||||
|
||||
@Query("SELECT * FROM location_history")
|
||||
fun getAll(): Flow<List<LocationEntity>>
|
||||
|
||||
@Query("SELECT COALESCE(MAX(tripId), 0) FROM location_history")
|
||||
suspend fun getMaxTripId(): Int
|
||||
|
||||
@Query("SELECT COUNT(DISTINCT tripId) FROM location_history")
|
||||
fun getTripCount(): Flow<Int>
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import androidx.room.RoomDatabase
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
|
||||
@Database(entities = [LocationEntity::class], version = 2)
|
||||
@Database(entities = [LocationEntity::class], version = 3)
|
||||
abstract class LocationDatabase : RoomDatabase() {
|
||||
|
||||
abstract fun locationDao(): LocationDao
|
||||
@@ -23,7 +23,7 @@ abstract class LocationDatabase : RoomDatabase() {
|
||||
LocationDatabase::class.java,
|
||||
"location_database"
|
||||
)
|
||||
.addMigrations(MIGRATION_1_2)
|
||||
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
INSTANCE = instance
|
||||
@@ -36,5 +36,12 @@ abstract class LocationDatabase : RoomDatabase() {
|
||||
// Since we are just adding new queries to the DAO, there is no need to alter the table.
|
||||
}
|
||||
}
|
||||
|
||||
private val MIGRATION_2_3 = object : Migration(2, 3) {
|
||||
override fun migrate(database: SupportSQLiteDatabase) {
|
||||
// Add tripId column with default value 0 for existing records
|
||||
database.execSQL("ALTER TABLE location_history ADD COLUMN tripId INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import androidx.room.PrimaryKey
|
||||
data class LocationEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Int = 0,
|
||||
val tripId: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val transportMode: String,
|
||||
|
||||
@@ -36,6 +36,7 @@ class LocationService : Service() {
|
||||
private val binder = LocationBinder()
|
||||
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private var transportMode: String = ""
|
||||
private var tripId: Int = 0
|
||||
|
||||
inner class LocationBinder : Binder() {
|
||||
fun getService(): LocationService = this@LocationService
|
||||
@@ -64,6 +65,8 @@ class LocationService : Service() {
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
Log.d("LocationService", "Service starting...")
|
||||
transportMode = intent?.getStringExtra("TRANSPORT_MODE") ?: ""
|
||||
tripId = intent?.getIntExtra("TRIP_ID", 0) ?: 0
|
||||
Log.d("LocationService", "Trip ID: $tripId, Transport Mode: $transportMode")
|
||||
try {
|
||||
startForeground(1, createNotification())
|
||||
startLocationUpdates()
|
||||
@@ -78,8 +81,8 @@ class LocationService : Service() {
|
||||
Log.d("LocationService", "startLocationUpdates called")
|
||||
val locationRequest = LocationRequest.Builder(
|
||||
Priority.PRIORITY_HIGH_ACCURACY,
|
||||
15000L // 15 seconds
|
||||
).setMinUpdateIntervalMillis(15000L).build()
|
||||
5000L // 5 seconds
|
||||
).setMinUpdateIntervalMillis(5000L).build()
|
||||
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
this, Manifest.permission.ACCESS_FINE_LOCATION
|
||||
@@ -106,13 +109,14 @@ class LocationService : Service() {
|
||||
val database = LocationDatabase.getDatabase(applicationContext)
|
||||
database.locationDao().insert(
|
||||
LocationEntity(
|
||||
tripId = tripId,
|
||||
latitude = location.latitude,
|
||||
longitude = location.longitude,
|
||||
transportMode = transportMode,
|
||||
timestamp = System.currentTimeMillis()
|
||||
)
|
||||
)
|
||||
Log.d("LocationService", "Location saved")
|
||||
Log.d("LocationService", "Location saved with tripId: $tripId")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,9 +17,11 @@ class LocationViewModel(application: Application) : AndroidViewModel(application
|
||||
val serviceRunning: LiveData<Boolean> = _serviceRunning
|
||||
private val _transportMode = MutableLiveData<String>("")
|
||||
val transportMode: LiveData<String> = _transportMode
|
||||
private val _currentTripId = MutableLiveData<Int>(0)
|
||||
val currentTripId: LiveData<Int> = _currentTripId
|
||||
|
||||
// Corrected: Use viewModelScope.coroutineContext to provide the necessary scope
|
||||
val locationCount: LiveData<Int> = locationDao.getCount().asLiveData(viewModelScope.coroutineContext + Dispatchers.IO)
|
||||
val tripCount: LiveData<Int> = locationDao.getTripCount().asLiveData(viewModelScope.coroutineContext + Dispatchers.IO)
|
||||
|
||||
fun updateServiceStatus(isRunning: Boolean) {
|
||||
_serviceRunning.value = isRunning
|
||||
@@ -29,6 +31,17 @@ class LocationViewModel(application: Application) : AndroidViewModel(application
|
||||
_transportMode.value = mode
|
||||
}
|
||||
|
||||
suspend fun getNextTripId(): Int {
|
||||
val maxTripId = locationDao.getMaxTripId()
|
||||
val nextTripId = maxTripId + 1
|
||||
_currentTripId.postValue(nextTripId)
|
||||
return nextTripId
|
||||
}
|
||||
|
||||
fun getCurrentTripId(): Int {
|
||||
return _currentTripId.value ?: 0
|
||||
}
|
||||
|
||||
fun checkServiceStatus(): Boolean {
|
||||
val manager = getApplication<Application>().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
|
||||
|
||||
@@ -45,6 +45,8 @@ import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
@@ -73,6 +75,7 @@ class MainActivity : ComponentActivity() {
|
||||
setContent {
|
||||
SuMoC_DemoTheme {
|
||||
val locationCount by viewModel.locationCount.observeAsState(0)
|
||||
val tripCount by viewModel.tripCount.observeAsState(0)
|
||||
val serviceRunning by viewModel.serviceRunning.observeAsState(false)
|
||||
val transportMode by viewModel.transportMode.observeAsState("")
|
||||
Surface(
|
||||
@@ -83,6 +86,7 @@ class MainActivity : ComponentActivity() {
|
||||
onStartClick = { requestLocationPermission() },
|
||||
onStopClick = { stopLocationWork() },
|
||||
locationCount = locationCount,
|
||||
tripCount = tripCount,
|
||||
serviceRunning = serviceRunning,
|
||||
transportMode = transportMode,
|
||||
onTransportModeChange = { viewModel.updateTransportMode(it) }
|
||||
@@ -131,15 +135,20 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
Log.d("MainActivity", "Starting LocationService")
|
||||
val intent = Intent(this, LocationService::class.java).apply {
|
||||
putExtra("TRANSPORT_MODE", viewModel.transportMode.value ?: "")
|
||||
// Get next trip ID in a coroutine and start the service
|
||||
lifecycleScope.launch {
|
||||
val tripId = viewModel.getNextTripId()
|
||||
val intent = Intent(this@MainActivity, LocationService::class.java).apply {
|
||||
putExtra("TRANSPORT_MODE", viewModel.transportMode.value ?: "")
|
||||
putExtra("TRIP_ID", tripId)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
startForegroundService(intent)
|
||||
} else {
|
||||
startService(intent)
|
||||
}
|
||||
viewModel.updateServiceStatus(true)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
startForegroundService(intent)
|
||||
} else {
|
||||
startService(intent)
|
||||
}
|
||||
viewModel.updateServiceStatus(true)
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(
|
||||
@@ -169,6 +178,7 @@ fun Control(
|
||||
onStartClick: () -> Unit,
|
||||
onStopClick: () -> Unit,
|
||||
locationCount: Int,
|
||||
tripCount: Int,
|
||||
serviceRunning: Boolean,
|
||||
transportMode: String = "",
|
||||
onTransportModeChange: (String) -> Unit = {}
|
||||
@@ -215,6 +225,7 @@ fun Control(
|
||||
Text(stringResource(R.string.stop_tracking))
|
||||
}
|
||||
Text(text = "Database entries: $locationCount")
|
||||
Text(text = "Trip count: $tripCount")
|
||||
Text(text = "Service status: ${if (serviceRunning) "Running" else "Stopped"}")
|
||||
}
|
||||
}
|
||||
@@ -223,6 +234,6 @@ fun Control(
|
||||
@Composable
|
||||
fun DemoAppPreview() {
|
||||
SuMoC_DemoTheme {
|
||||
Control(onStartClick = {}, onStopClick = {}, locationCount = 0, serviceRunning = false)
|
||||
Control(onStartClick = {}, onStopClick = {}, locationCount = 0, tripCount = 0, serviceRunning = false)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user