Reputation: 304
I'm still getting used to Jetpack Compose and I'm trying to get ahold of the phone sensors, specifically the accelerometer in this case, but it could be anything...
In a standard Activity flow, I'd get an instance of SensorManager and go from there, but given the focus on Routes that Jetpack Compose goes for, I'm at a loss as to how to perform such a task. We have one MainActivity.kt from within which the Navigation is handled.
Do I truly have to pass the SensorManager instance all the way down to my Composable? It seems excessive to simply detect a device shake... If the device shakes, perform this in the Composable...
In the bigger picture, this question also applies to anything you'd do in standard lifecycle methods I guess... In a Header(...){} component, I do not have any access to an onCreate method. Am I to understand that if composables need to depend of lifecycle, I have to bubble everything back up the tree similar to what you would do in React without Redux for instance?
The Compose docs specifically mention that state can be managed for "something like sensors", but how do your retrieve the elements you need to have access to these sensors?
I appreciate the help, as always.
Upvotes: 7
Views: 3287
Reputation: 364556
You can use:
@Composable
fun myComposable() {
val sensorManager = LocalContext.current.getSystemService(SENSOR_SERVICE) as SensorManager
//...
}
Upvotes: 5