Skip to content

Commit

Permalink
New Feature
Browse files Browse the repository at this point in the history
Users can now select and deselect sensors from the list while streaming. This allows the app to send data from different sensors dynamically, without needing to stop and restart the stream."
  • Loading branch information
umer0586 committed Oct 10, 2024
1 parent f26038e commit 769c8c7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,13 @@ class SensorStreamingService : Service() {
sensors = settingsRepository.selectedSensors.first().toSensors(applicationContext)
)

scope.launch {

settingsRepository.selectedSensors.collect{
sensorStreamer?.changeSensors(it.toSensors(applicationContext))
}
}

sensorStreamer?.onStreamingStarted { info ->
streamingStartedCallBack?.invoke(info)
val notificationIntent = Intent(applicationContext, MainActivity::class.java)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class SensorStreamer(
val address: String,
val portNo: Int,
val samplingRate : Int,
val sensors: List<Sensor>
private var sensors: List<Sensor>
) : SensorEventListener {


Expand Down Expand Up @@ -122,6 +122,31 @@ class SensorStreamer(
onError = callBack
}

fun changeSensors(newSensors : List<Sensor>){

if(!isStreaming)
return

sensors.forEach {
sensorManager.unregisterListener(this, it)
}

newSensors.forEach{
sensorManager.registerListener(this, it, samplingRate, handler)
}

// Avoid declaring 'sensors' property as a mutable list and then doing 'sensors.clear()' followed by 'sensors.addAll(newSensors)'.
// This can throw a ConcurrentModificationException, leading to app crashes.
// The crash occurs because the list is being modified while it's being iterated over,
// which happens when the user frequently selects and deselects sensors from the list during streaming.
//
// One solution is to use an iterator, as explained here: https://stackoverflow.com/questions/50032000/how-to-avoid-concurrentmodificationexception-kotlin
// Alternatively, declaring 'sensors' as a 'var' and reassigning it (tested and works without crashes) is a simpler and effective fix.

sensors = newSensors

}

override fun onSensorChanged(sensorEvent: SensorEvent) {

val sensorData = mutableMapOf<String,Any>()
Expand Down

0 comments on commit 769c8c7

Please sign in to comment.