Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Android Sensors with Example
Next article icon

Android Sensors with Example

Last Updated : 08 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
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: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.


 


Next Article
Android Sensors with Example

I

iamabhijha
Improve
Article Tags :
  • Kotlin
  • Android

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences