whoami
Lucas Jenß
cat /etc/motd
The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.
ls -la ~/languages/
- drwxr-xr-x
- ▶ PHP
- ▶ Ruby
- ▶ Scala
- ▶ C#
- ▶ JavaScript
- ▶ Objective-C
- ▶ Shell Scripting
ls -la ~/toolchain/
- drwxr-xr-x
- ▶ Typo3
- ▶ Akka
- ▶ Capistrano
- ▶ Git
- ▶ MAMP
- ▶ Adobe Illustrator
- ▶ NSTrackingArea (Cocoa)
uname -a
- drwxr-xr-x
- ▶ Mac OS X
- ▶ Unix
Reading Android sensors from native C
Using the Android NDK to access hardware sensors from C code can keep an existing native pipeline in one language. Instead of moving every accelerometer or gyroscope sample through JNI, an application can read events through the NDK sensor API and process them beside its other C or C++ components. The platform still owns the drivers and scheduling.
The distinction is between making a sensor readable and building a dependable feature. Native code must still follow Android permissions, activity lifecycles, thread rules and device-specific timing. The NDK therefore fits inside an Android app; it does not remove the safeguards around background work or personal data.
This walkthrough covers a compact C implementation, the Gradle and CMake setup that packages it, and the checks I would use before trusting its output. The aim is an inspectable path from hardware event to native calculation: acquire, validate, record, then compare the trace with the platform API.
| Approach | Language | Permissions | Best fit |
|---|---|---|---|
| Android Sensor API | Java or Kotlin | Platform rules apply | General applications and simple integrations |
| NDK sensor API | C or C++ | Platform rules still apply | Existing native pipelines and custom processing |
| Vendor or USB bridge | C, C++ or vendor tools | Depends on the hardware | Specialist sensors outside the handset |
| Captured-event replay | Test harness | None required | Deterministic algorithm tests |
Choose the native sensor boundary
The NDK is a good fit when existing C/C++ code already owns signal processing, or when allocating Java or Kotlin objects on every sample would get in the way. A native filter can consume events, apply calibration and pass a compact result to the interface. For a simple orientation display, Android’s framework API usually requires less machinery.
Native access does not guarantee better data or a higher sampling rate. Hardware support, batching and latency depend on the handset, and the package-aware manager used here requires API level 26. Supporting older releases means using a compatibility path or choosing a different minimum SDK, not quietly assuming a desktop sensor stack is equivalent.
Prepare the Android build
Package the C source as a native shared library. A CMake file locates the Android sensorservice library, while the app’s Gradle configuration selects the NDK version and target ABIs. The sensor code must be compiled against Android headers from the SDK; a successful build on macOS, Linux or Windows proves only that the host compiler is happy.
find_package(android REQUIRED COMPONENTS sensorservice log)
add_library(native_sensors SHARED sensors.c)
target_compile_features(native_sensors PRIVATE c_std_17)
target_link_libraries(native_sensors PRIVATE android sensorservice log)
Configure externalNativeBuild in the app module and keep compileSdk and targetSdk aligned with current Play requirements. Check that arm64-v8a is included for physical devices and x86_64 for an emulator; older 32-bit-only builds no longer satisfy current Google Play release requirements. The package name must come from Context.getPackageName(), since ASensorManager_getInstanceForPackage needs the identifier assigned to this app.
The software-development notes in Oscar’s coding journal are a useful companion when the build boundary is hard to see. Keep a minimal native library, inspect its symbols in the packaged APK and remove unnecessary ABIs only after measuring real device coverage.
Connect sensors to a native event queue
Create the manager with the application package name, select a sensor such as ASENSOR_TYPE_ACCELEROMETER, and attach an ASensorEventQueue to the thread’s ALooper. The queue lets sensor wake-ups become work on that thread, which keeps the event path aligned with the activity’s native execution rather than polling from an arbitrary background thread.
ASensorManager *manager =
ASensorManager_getInstanceForPackage(package_name);
ASensor *accelerometer =
ASensorManager_getDefaultSensor(manager, ASENSOR_TYPE_ACCELEROMETER);
/* Check manager and accelerometer before continuing. */
int min_delay_us =
ASensorManager_getMinDelay(manager, accelerometer);
int period_us = min_delay_us > 10000 ? min_delay_us : 10000;
ALooper *looper = ALooper_forThread();
ASensorEventQueue *queue =
ASensorManager_createEventQueue(manager, looper, 1);
/* Check queue before enabling the sensor. */
ASensorEventQueue_enableSensor(queue, accelerometer);
ASensorEventQueue_setEventRate(queue, accelerometer, period_us);
This requests roughly 100 Hz without asking for a rate faster than the device reports as its minimum delay. Check every returned pointer before enabling the sensor and keep the package-name string alive for the call. When the feature pauses, disable the sensor and call ASensorManager_destroyEventQueue; enable it again only after confirming that the device configuration remains valid.
Read and interpret sensor events
Pump the looper and then call ASensorEventQueue_getEvents to copy ASensorEvent structures from the queue. The event timestamp is monotonic nanoseconds, not a wall-clock date. Accelerometer values include gravity and use m/s², so a phone resting flat reads roughly 9.81 on one axis. Gyroscope values are angular velocity in radians per second.
Work in the device coordinate system: in the default portrait orientation, x points right, y points up and z points out of the screen. Remap those axes when the interface rotates, and do not mistake a stationary reading for zero acceleration. Track the sensor’s reported accuracy and flag implausible jumps rather than feeding them straight into a filter.
For visual checks of recorded traces, SVG export can expose bad axes or discontinuities. My Adobe Illustrator import quirks notes cover common import failures in older Illustrator releases. That cleanup habit belongs beside the sensor maths: a polished drawing can still conceal incorrect data.
Handle permissions and lifecycle changes
The native path does not bypass Android’s permission model. Accelerometers and gyroscopes generally need no body-sensor runtime permission, but step counting requires ACTIVITY_RECOGNITION on Android 10 and later. A heart-rate feature involves BODY_SENSORS, while sampling above 200 Hz is affected by HIGH_SAMPLING_RATE_SENSORS on Android 12 and later. Declare only what the feature uses.
Tie the sensor lifetime to a visible feature or a correctly declared foreground service instead of leaving it active after the screen closes. Disable it in the pause path, retain the last sample for redisplay and re-enable it when work resumes. The Java or Kotlin layer should request runtime access before C attempts registration.
For a commercial release, check whether the Privacy Act 1988 and the Australian Privacy Principles apply to the organisation and its data. Sensor-derived information can become personal information when linked to a person. Publish a clear collection notice, restrict access to stored traces and avoid turning a movement sensor into an activity profile without a justified purpose.
Test on real devices and emulators
An emulator is useful for checking event delivery, but simulated acceleration cannot reproduce vibration, drift or calibration differences. Use the virtual sensor controls for repeatable movement, then run the same native binary on physical handsets. Android’s strong presence in Australia’s handset market makes this testing mix essential, and Pixel and Samsung models sold through Telstra, Optus and Vodafone Australia provide a useful spread of sensors and firmware.
Test situations that resemble everyday use. A Sydney or Melbourne train journey can lose GNSS in a tunnel; inertial readings may bridge a brief gap, though they are not a substitute for navigation. Express speed in km/h and temperature in °C to match Australian signs and forecasts, and verify unit conversion at the native boundary rather than only in the interface.
Keep a repeatable motion script, such as a slow tilt followed by a short walk, and record the raw samples. Compare event counts and timestamps across runs so a scheduling regression is distinguishable from ordinary sensor noise.
Build, measure and share
Make the pipeline observable. Log the sensor type, requested rate, delivered rate and error status, and include the device model and Android release in test records. A trace containing every event separates a filter bug from a dropped queue event, while a small summary keeps production logs manageable.
Start with one sensor and compare it against Android’s framework implementation on the same handset. Keep the C boundary narrow, record the minimum supported API level and publish useful findings in The Coding Journal. Subscribe for more native-development notes and share the results of your first native sensor test.
cat ~/interests.json
| Key | Value |
|---|---|
| editor | Terminal-first workflow |
| os | Mac OS X / Unix |
| vcs | Git, distributed version control |
| deploy | Capistrano, cron automation |
| graphics | SVG, Adobe Illustrator troubleshooting |
| networking | IP validation, SSH, VPN |
git log --oneline --reverse
Solving SVG import issues in Adobe Illustrator CS6 and CC
When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.
Solving NDK build issues on OS X
Troubleshooting native development kit compilation problems on Mac OS X.
Programmatically adding PHP generated TypoScript to the backend configuration
Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.
ArgumentError: Could not parse PKey: no start line
Debugging an SSH key parsing error encountered during deployment.
Validating IP-Addresses in PHP
Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.
Cocoa: Using NSTrackingArea
A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.
cat ~/contact.txt