Created
October 11, 2019 14:42
-
-
Save bananaumai/5b2a53f7f00a9875f3947f3618ef32ee to your computer and use it in GitHub Desktop.
Sensor Flow with lifecycleScope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ExperimentalCoroutinesApi | |
class MainActivity : AppCompatActivity() { | |
private var working = false | |
private var job: Job? = null | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val button = findViewById<Button>(R.id.button) | |
button.setOnClickListener { | |
button.isEnabled = false | |
working = !working | |
if (working) { | |
button.text = "stop" | |
start() | |
} else { | |
stop() | |
button.text = "run" | |
} | |
button.isEnabled = true | |
} | |
} | |
private fun start() { | |
job = lifecycleScope.launch { | |
accelerometerFlow(this@MainActivity) | |
.collect { | |
Log.d("MainActivity", "$it") | |
} | |
} | |
} | |
private fun stop() { | |
job?.cancel() | |
} | |
} | |
@ExperimentalCoroutinesApi | |
fun accelerometerFlow(context: Context) = channelFlow { | |
val handlerThread = HandlerThread("test", Process.THREAD_PRIORITY_BACKGROUND).apply { start() } | |
val handler = Handler(handlerThread.looper) | |
val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager | |
val sensorEventListener = object : SensorEventListener { | |
override fun onSensorChanged(event: SensorEvent?) { | |
Log.v("accelerometerFlow", "$event") | |
CoroutineScope(coroutineContext).launch { | |
send(event?.values?.toList()) | |
} | |
} | |
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} | |
} | |
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION) | |
sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL, handler) | |
awaitClose { | |
sensorManager.unregisterListener(sensorEventListener, sensor) | |
handlerThread.quitSafely() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment