Android Sensors with Example
Last Updated : 08 Feb, 2022
In our childhood, we all have played many android games like Moto Racing and Temple run in which by tilting the phone the position of the character changes. So, all these happen because of the sensors present in your Android device. Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions. Android Sensors can be used to monitor the three-dimensional device movement or change in the environment of the device such as light, proximity, rotation, movements, magnetic fields, and much more.
Types of Sensors
- Motion Sensors: These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
- Position Sensors: These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.
- Environmental Sensors: These sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.
Android Sensor API
We can collect raw sensor data by using Android Sensor API. Android sensor API provides many classes and interfaces. Some of the important classes and interfaces are:
- SensorManager Class: Sensor manager is used to accessing various sensors present in the device.
- Sensor Class: The sensor class is used to get information about the sensor such as sensor name, sensor type, sensor resolution, sensor type, etc.
- SensorEvent class: This class is used to find information about the sensor.
- SensorEventListener interface: This is used to perform some action when sensor accuracy changes.
Example: Light Sensor App
This app will show us light intensity in our room with the help of a light sensor present in our phone.
Step by Step Implementation
Step 1: Create a New Project in your android studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the XML file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file.
XML <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Textview to show light sensor reading --> <TextView android:id="@+id/tv_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Light Sensor" android:textSize="20sp" android:textColor="@color/black" android:layout_centerInParent="true" /> </RelativeLayout>
Step 3: Working With the MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin package com.mrtechy.gfg_sensor import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatDelegate class MainActivity : AppCompatActivity(), SensorEventListener { // Initialised sensorManager & two variables // for storing brightness value private lateinit var sensorManager: SensorManager private var brightness: Sensor? = null private lateinit var text: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Set default nightmode AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) // searched our textview id and stored it text = findViewById(R.id.tv_text) // setupSensor Called setUpSensor() } // Declared setupSensor function private fun setUpSensor() { sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager brightness = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) } // These are two methods from sensorEventListner Interface override fun onSensorChanged(event: SensorEvent?) { if (event?.sensor?.type == Sensor.TYPE_LIGHT) { val light1 = event.values[0] text.text = "Sensor: $light1\n${brightness(light1)}" } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { return } // Created a function to show messages according to the brightness private fun brightness(brightness: Float): String { return when (brightness.toInt()) { 0 -> "Pitch black" in 1..10 -> "Dark" in 11..50 -> "Grey" in 51..5000 -> "Normal" in 5001..25000 -> "Incredibly bright" else -> "This light will blind you" } } // This is onResume function of our app override fun onResume() { super.onResume() sensorManager.registerListener(this, brightness, SensorManager.SENSOR_DELAY_NORMAL) } // This is onPause function of our app override fun onPause() { super.onPause() sensorManager.unregisterListener(this) } }
Output:
Note: App those usage sensors will only work on physical Android devices, not on any emulators.
Similar Reads
OpenIntents in Android with Example OI refers to the "OpenIntents" project in Android are a way for one app to request an action from another app. This can be done using either explicit or implicit intents, allowing them to share functionality. The OpenIntents project provides a set of commonly-used intents that can be used by develop
4 min read
PhotoView in Android with Example In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displa
2 min read
How to Use FFmpeg in Android with Example? FFmpeg, short for Fast-forward MPEG, is a free and open-source multimedia framework, which is able to decode, encode, transcode, mux, demux, stream, filter and play fairly all kinds of multimedia files that have been created to date. It also supports some of the eldest formats. FFmpeg compiles and r
15+ min read
Android ListView in Java with Example A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with each item positioned one below the other. Using an adapter, items are inserted into the list from an array or database efficiently. For displaying the items in the list method setAdaptor() is use
3 min read
Testing an Android Application with Example Testing is an essential part of the Android app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. Android offers various testing tools and frameworks that can be used to write and execute different types of tests, including
5 min read