Triggering an event on phone movement, React Native and Expo

Lily Lebec
2 min readJan 24, 2018

--

Our phones now incorporate a wide variety of sensors that measure motion and orientation so that you can monitor three-dimensional device movement or positioning. They are the one used to track our steps and activity fitness for example, or the tilt, shake of a phone for a video game.

Accelerometers in mobile phones are used to detect the orientation of the phone. The gyroscope adds an additional dimension to the information supplied by the accelerometer by tracking rotation or twist. Those are motion sensors, monitoring device movement.

We can access the Accelerometers with Expo SDK, a library that provides a wide variety of native APIs on iOS and Android.
The goal is to trigger an event based on phone orientation. For example, if you lift up your phone or turn it around, you are added in a queue.

The first thing is to import Accelerometer from expo. This expo object is derived from the ThreeAxisSensor derived from the native sensor of our phone.
One important point is that on average, your most power hungry sensors are the GPS, accelerometer and gyroscope. This is why you want to subscribe to listening to the Accelerometer on ComponentDidMount and want to unsubscribe on ComponentWillUnmount. Subscribing to our Accelerometer simply means to add an event listener to it. On having the component mount, we want to start saving our {x, y z} data in our local state.

The event will be triggered if y coordinate is above 0.7.
We are communicating through socket, which can be problematic with Android. It will fire up the following error message:

Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground.

You can fix this issue by adding a “heart beat” to your socket io on your back-end with pingTimeout( how many ms without a pong packet to consider the connection closed).

const io = require('socket.io')(server, {pingTimeout: 30000})

When sending socket io event emitter when an event is triggered, it may fire it up many time, so setting pingInterval ( how many ms before sending a new ping packet) helps. We may as well make use of the ‘debounce’ function to only trigger the function once every other milliseconds to avoid packet of socket io messages!

Thats it!

--

--