Android SharedPreferences Tutorial and Example

Building a Sensor Data Monitor App on Android

A sensor data monitor app turns readings from an Android phone into useful, visible information. With the Sensor Framework, you can display movement, orientation, light, pressure and other measurements in real time. This makes a practical project for learning Kotlin, event listeners, layouts, lifecycle handling and local data storage.

The app described here uses a simple dashboard with live values, a start and stop control, and a small history log. It can support field testing on a bushwalk in the Blue Mountains, motion experiments on a Melbourne tram, or a classroom demonstration anywhere in Australia. The same structure can later be extended with charts, alerts and cloud synchronisation.

Choose Sensors And Define Data

Android devices commonly provide an accelerometer, gyroscope, magnetometer, light sensor, proximity sensor and barometer. Availability varies between handsets, so the app should check each sensor before trying to use it. A Google Pixel, Samsung Galaxy or budget Android phone may expose a different selection of hardware.

For a first version, use the accelerometer because it is widely available and easy to understand. It reports force along the X, Y and Z axes in metres per second squared. Add the light sensor as a second example, displaying illumination in lux. A pressure sensor can be useful for altitude experiments, although weather changes around places such as Brisbane or Perth can affect its readings.

Create a small data model so each reading has a timestamp, sensor type and values. Keeping this structure separate from the user interface makes it easier to save records in SQLite or export them as CSV later.

Create The Android Project And Sensor Manager

Start an Android Studio project using Kotlin and a modern Android SDK. Add a screen containing TextViews for the sensor name and current values, a status label, and buttons for starting and stopping monitoring. A ScrollView or RecyclerView can show recent samples without making the layout difficult to manage.

The central Android class is SensorManager. Retrieve it from the application context and request the required sensor:

private lateinit var sensorManager: SensorManager
private var accelerometer: Sensor? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    sensorManager =
        getSystemService(Context.SENSOR_SERVICE) as SensorManager

    accelerometer =
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
}

A nullable sensor reference is important. If the device has no accelerometer, show a clear message such as “Accelerometer unavailable” instead of allowing the app to fail. This is particularly helpful when testing across different Android phones used by Australian customers.

Build The Live Monitoring Screen

Implement SensorEventListener in the Activity or, preferably, in a lifecycle-aware component. The listener receives a SensorEvent containing the sensor object, a float array of values and an event timestamp. For an accelerometer, the first three values represent the X, Y and Z axes.

override fun onSensorChanged(event: SensorEvent) {
    if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
        val x = event.values[0]
        val y = event.values[1]
        val z = event.values[2]

        valuesText.text = String.format(
            Locale.US,
            "X: %.2f\nY: %.2f\nZ: %.2f",
            x, y, z
        )
    }
}

Use Locale.US or an explicitly controlled number format when creating machine-readable output. Australian users normally expect decimal values and metric units, while exported files should use a consistent format regardless of the device language. A timestamp such as 2025-03-08 14:35:12 is easier to sort than a casual display string.

Sensor callbacks can arrive many times each second. Updating a complex chart or database on every callback may cause poor performance. For the dashboard, update the visible values frequently, but sample data at a controlled interval such as 250 or 500 milliseconds.

Register Listeners Safely

Register the listener when monitoring begins and remove it when monitoring stops. The selected delay controls how often Android attempts to deliver events. SENSOR_DELAY_UI suits a dashboard, while SENSOR_DELAY_GAME produces faster updates and uses more battery.

private fun startMonitoring() {
    accelerometer?.let { sensor ->
        sensorManager.registerListener(
            this,
            sensor,
            SensorManager.SENSOR_DELAY_UI
        )
        statusText.text = "Monitoring"
    }
}

private fun stopMonitoring() {
    sensorManager.unregisterListener(this)
    statusText.text = "Stopped"
}

Also unregister listeners in onPause() or onStop() if the screen does not need background collection. Sensors can drain a phone quickly during a long train trip on Sydney’s rail network or while recording data during a full day outdoors. When background monitoring is essential, use a foreground service and show an ongoing notification.

The onAccuracyChanged() callback can update a small warning when the sensor becomes unreliable. A magnetometer may need calibration near vehicles, metal structures or electrical equipment. Providing a reset or calibration instruction helps users interpret unexpected values.

Store And Export Sensor Readings

For a short session, keep recent readings in a mutable list and display them in a RecyclerView. For longer sessions, use Room over SQLite so records remain available after the Activity is recreated. A suitable entity might contain an ID, sensor type, timestamp, X value, Y value and Z value.

Avoid writing to the database directly from the sensor callback. Instead, collect a sample at a fixed interval and insert it on a background coroutine. This reduces disk activity and leaves the main thread available for smooth UI updates. A maximum history size also prevents an unattended monitor from filling storage.

CSV export is useful for students, developers and field researchers. Include column names such as timestamp,sensor,x,y,z,unit. A person comparing temperature-related activity in Darwin with cooler conditions in Hobart can then analyse the results in a spreadsheet, provided the app records the device time zone and sampling interval.

Test Accuracy Battery And Privacy

Test the app on a physical phone because the Android emulator cannot reproduce every hardware sensor accurately. Place the device flat, rotate it, walk with it and create controlled movements. For light readings, compare indoor values with outdoor conditions, but avoid treating a phone sensor as a certified instrument.

Keep the interface readable in bright Australian sunlight and support dark mode for evening use. Test with large text, landscape orientation and intermittent connectivity. The app does not need internet access for local sensor monitoring, which is helpful in remote areas such as regional Queensland or on roads outside mobile coverage.

Sensor readings can reveal movement patterns, location context and daily routines even when the app does not request GPS. Explain what is collected, provide a delete-history action and avoid uploading data by default. If readings are sent to a server, apply Australian privacy requirements and give users a clear purpose for collection.

The following design choices help match the feature to a particular Android project:

Monitoring Approach Best Use Advantages Limitations
Live Text Values Learning and quick diagnostics Simple layout and low processing cost Does not reveal long-term patterns
RecyclerView History Short measurement sessions Easy to browse recent samples Memory use grows without a limit
Room Database Repeated or extended monitoring Persistent, searchable local records Requires schema and background work
CSV Export Spreadsheet analysis and reports Portable and easy to inspect Offers limited visualisation
Foreground Service Monitoring while the app is hidden Continues beyond the visible screen Requires notification and careful battery management

A well-structured sensor data monitor app begins with one reliable sensor and a clear display. Once lifecycle handling, sampling, storage and privacy are working correctly, you can add a chart, threshold alerts, calibration tools or support for several sensors without rewriting the core design.