Open In App

Android Sensors with Example

Last Updated : 08 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

  1. Motion Sensors: These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
  2. Position Sensors: These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.
  3. 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:

  1. SensorManager Class: Sensor manager is used to accessing various sensors present in the device.
  2. Sensor Class: The sensor class is used to get information about the sensor such as sensor name, sensor type, sensor resolution, sensor type, etc.
  3. SensorEvent class: This class is used to find information about the sensor.
  4. 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: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.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads