Accelerometer in Mobile Apps: A Practical Guide
Use the accelerometer in iOS and Android apps to detect motion, orientation, shake gestures and steps — with copy-pasteable Expo, Swift and Kotlin code.
The accelerometer is the workhorse motion sensor in every modern smartphone. It measures linear acceleration on three axes, which is the raw signal behind features like screen rotation, step counting, shake-to-undo and physics-based games. This guide shows you exactly how to read it from a React Native app via Expo, an iOS app via Core Motion, and an Android app via SensorManager — and how to avoid the most common bugs.
Key Takeaways
- The accelerometer reports acceleration in m/s² on three axes, including gravity (~9.81 on whichever axis points down).
- In Expo, expo-sensors gives you a single API that works on iOS and Android — no native code required.
- On iOS use Core Motion (CMMotionManager); on Android use SensorManager with TYPE_ACCELEROMETER or the sensor-fusion variants.
- Set a sample rate (interval) you actually need — 60 Hz is fine for shake detection, 100 Hz+ drains the battery.
Accelerometer at a Glance
What It Is & How It Works
What it is. A MEMS (micro-electro-mechanical system) chip that measures proper acceleration along three orthogonal axes. When the device is at rest, it still reports a vector roughly equal to gravity, because the casing is being pushed up against free-fall.
How it works. A tiny mass on springs deflects when the device accelerates; capacitive plates measure the deflection and convert it to a numeric reading. The OS exposes that reading through a sensor framework and lets you subscribe to a sample stream at the rate you choose.
Units & signal. iOS Core Motion reports acceleration in g (multiples of standard gravity ≈ 9.81 m/s²). Android and Expo report in m/s². When the device sits flat on a table you should see roughly { x: 0, y: 0, z: 1 g } on iOS or { x: 0, y: 0, z: 9.81 m/s² } on Android.
What You Can Build With It
Shake to undo or refresh
Detect quick changes in acceleration magnitude to trigger an action like undoing the last edit or pulling fresh data.
Example: A note-taking app that pops a "Shake to undo" toast.
Step counting and pedometers
Combine acceleration peaks with simple low-pass filtering to count steps without a dedicated step sensor.
Example: A fitness app that estimates steps when CoreMotion pedometer is unavailable.
Tilt and physics games
Use the accelerometer as a steering input — the X/Y axes map naturally to a 2D rolling-ball or labyrinth game.
Example: A casual game where tilting the phone rolls a marble around a maze.
Drop / impact detection
Spikes in the magnitude of the acceleration vector indicate the device was dropped or struck — useful for safety apps.
Example: A fall-detection feature in an elder-care companion app.
Permissions & Setup
iOS will prompt the user the first time you read motion data — your Info.plist NSMotionUsageDescription string is what the user sees. Android does not require a runtime permission for the accelerometer, but it still pays to explain why you are using it in your privacy policy.
iOS · Info.plist
NSMotionUsageDescription
Android · AndroidManifest.xml
No special permission keys required.
On iOS the prompt appears as part of the Motion & Fitness permission set. If the user denies it, your subscription will silently return zeros.
Code Examples
In all three stacks the pattern is the same: configure the sampling interval, subscribe to a stream of {x, y, z} samples, and unsubscribe when the screen leaves view.
Setup
- Expo: `npx expo install expo-sensors`
- iOS: link CoreMotion (automatic in Xcode), add `NSMotionUsageDescription` to Info.plist
- Android: no permission, but request the default accelerometer from `SensorManager`
import { useEffect, useState } from 'react';
import { Accelerometer } from 'expo-sensors';
import { Text, View } from 'react-native';
export function AccelerometerView() {
const [data, setData] = useState({ x: 0, y: 0, z: 0 });
useEffect(() => {
Accelerometer.setUpdateInterval(100); // ms — ~10 Hz is plenty for UI
const sub = Accelerometer.addListener(setData);
return () => sub.remove();
}, []);
const magnitude = Math.sqrt(data.x ** 2 + data.y ** 2 + data.z ** 2);
return (
<View>
<Text>x: {data.x.toFixed(2)}</Text>
<Text>y: {data.y.toFixed(2)}</Text>
<Text>z: {data.z.toFixed(2)}</Text>
{magnitude > 2.5 && <Text>📳 Shake detected</Text>}
</View>
);
}Tip: With Newly, you describe the feature you want and the AI agent wires up the sensor, permissions, and UI for you. Try it free.
Best Practices
Match the sample rate to the use case
Pick the slowest rate that still works — 10–20 Hz for tilt UIs, 50 Hz for shake/steps, 100 Hz+ only for sports analytics. Higher rates cost battery linearly.
Always unsubscribe in cleanup
Forgetting to remove listeners on unmount/dealloc is the #1 cause of phantom CPU usage. Use useEffect cleanup, deinit, or onDispose.
Filter the signal before reacting to it
Raw accelerometer data is noisy. A simple low-pass filter (or moving average over 3–5 samples) eliminates most false triggers in shake/step detection.
Test on a real device, not the simulator
iOS Simulator and Android Emulator do not provide real motion data. Use Xcode "Device > Simulate Location" hacks or just plug in a phone.
Common Pitfalls
Forgetting that gravity is in the signal
TYPE_ACCELEROMETER and Core Motion accelerometer both include gravity. A device flat on a table reports ~9.81 m/s² on Z, not 0.
Mitigation: For motion-only data, use Linear Acceleration (TYPE_LINEAR_ACCELERATION on Android, deviceMotion.userAcceleration on iOS).
Crashing when the sensor is missing
Some tablets and feature phones do not have a usable accelerometer; reading from a null sensor throws.
Mitigation: Always check `isAccelerometerAvailable` (iOS) or `getDefaultSensor()` returning null (Android) before subscribing.
Polling on the main thread
Heavy filtering or React state updates on every sample at 100 Hz can drop frames in the UI.
Mitigation: Throttle React state updates (e.g. update at 10 Hz, integrate at 100 Hz), or use a worklet via Reanimated.
Skipping the iOS prompt copy
A vague NSMotionUsageDescription leads users to deny the prompt, leaving you with silent zero readings.
Mitigation: Write a one-sentence, benefit-driven string like "Used to detect when you shake to undo your last action."
When To Use It (And When Not To)
Good fit
- Shake / drop / impact detection
- Tilt-based controls and 2D physics games
- Lightweight step or activity counting when no Activity API is available
- Gimbal-like camera UIs that follow device orientation
Look elsewhere if…
- High-precision orientation — use the rotation vector or device motion fusion instead
- GPS-grade movement tracking — accelerometer alone drifts within seconds
- Background motion monitoring on iOS without Always-on entitlement
- Health-grade step counting — the platform pedometer is more accurate
Frequently Asked Questions
Does using the accelerometer drain the battery?
It is one of the cheapest sensors to run, but the cost scales linearly with sample rate. 10 Hz for an hour is negligible; 200 Hz for an hour is noticeable. Always pick the slowest rate that gives you the signal you need.
How do I detect a shake gesture?
Subscribe at 50–100 Hz, compute the magnitude `sqrt(x²+y²+z²)`, and look for two or three peaks above ~2 g within 500 ms. On iOS you can also use UIResponder `motionEnded(_:with:)` for free.
Can I read the accelerometer in the background?
Android: yes, with a foreground service. iOS: only via Core Motion in specific scenarios (CMMotionActivityManager, HealthKit). General-purpose background streaming is not allowed.
What is the difference between accelerometer and linear acceleration?
The accelerometer includes gravity in its reading. Linear acceleration is the same data with gravity subtracted out, so a stationary device reads ~0 on all axes. Use linear acceleration for "is the device moving?" questions.
Build with the Accelerometer on Newly
Ship a accelerometer-powered feature this week
Newly turns a description like “use the accelerometer to shake to undo or refresh” into a real React Native app — permissions, native modules and UI included. Full source code is yours, and you can publish to the App Store and Google Play directly from the dashboard.
Want a deeper dive on the underlying APIs? See Expo Sensors, Apple Core Motion and Android sensor framework.
Continue Learning
Gyroscope in Mobile Apps →
Combine the gyroscope with the accelerometer for real orientation tracking.
Linear Acceleration Sensor →
The gravity-removed sibling of the raw accelerometer.
Rotation Vector Sensor →
A fused orientation sensor that beats raw accelerometer + gyro maths.
Build Mobile Apps Without Coding →
Generate sensor-aware mobile apps from a description with Newly.
