Skip to content

Commit 769c8c7

Browse files
committed
New Feature
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."
1 parent f26038e commit 769c8c7

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

app/src/main/java/com/github/umer0586/sensagram/model/service/SensorStreamingService.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,13 @@ class SensorStreamingService : Service() {
118118
sensors = settingsRepository.selectedSensors.first().toSensors(applicationContext)
119119
)
120120

121+
scope.launch {
122+
123+
settingsRepository.selectedSensors.collect{
124+
sensorStreamer?.changeSensors(it.toSensors(applicationContext))
125+
}
126+
}
127+
121128
sensorStreamer?.onStreamingStarted { info ->
122129
streamingStartedCallBack?.invoke(info)
123130
val notificationIntent = Intent(applicationContext, MainActivity::class.java)

app/src/main/java/com/github/umer0586/sensagram/model/streamer/SensorStreamer.kt

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class SensorStreamer(
4545
val address: String,
4646
val portNo: Int,
4747
val samplingRate : Int,
48-
val sensors: List<Sensor>
48+
private var sensors: List<Sensor>
4949
) : SensorEventListener {
5050

5151

@@ -122,6 +122,31 @@ class SensorStreamer(
122122
onError = callBack
123123
}
124124

125+
fun changeSensors(newSensors : List<Sensor>){
126+
127+
if(!isStreaming)
128+
return
129+
130+
sensors.forEach {
131+
sensorManager.unregisterListener(this, it)
132+
}
133+
134+
newSensors.forEach{
135+
sensorManager.registerListener(this, it, samplingRate, handler)
136+
}
137+
138+
// Avoid declaring 'sensors' property as a mutable list and then doing 'sensors.clear()' followed by 'sensors.addAll(newSensors)'.
139+
// This can throw a ConcurrentModificationException, leading to app crashes.
140+
// The crash occurs because the list is being modified while it's being iterated over,
141+
// which happens when the user frequently selects and deselects sensors from the list during streaming.
142+
//
143+
// One solution is to use an iterator, as explained here: https://stackoverflow.com/questions/50032000/how-to-avoid-concurrentmodificationexception-kotlin
144+
// Alternatively, declaring 'sensors' as a 'var' and reassigning it (tested and works without crashes) is a simpler and effective fix.
145+
146+
sensors = newSensors
147+
148+
}
149+
125150
override fun onSensorChanged(sensorEvent: SensorEvent) {
126151

127152
val sensorData = mutableMapOf<String,Any>()

0 commit comments

Comments
 (0)