Android Sensors with Example - GeeksforGeeks

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.
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.
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.
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.
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.
This app will show us light intensity in our room with the help of a light sensor present in our phone.
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.Sensorimport android.hardware.SensorEventimport android.hardware.SensorEventListenerimport android.hardware.SensorManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport 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.
 
sagartomar9927
prachisoda1234
avtarkumar719
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Kotlin Array
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
Android Menus
Kotlin Setters and Getters