Create Sensor Android App Using Android Studio

Introduction

 
In this article, I will show you how to create a Sensor Android App using Android Studio. We are going to create a sensor application that changes the background color of an activity when the device is shaken.
 
 Requirements
Types of Sensors
 
Android supports three types of sensors,
  1. Motion Sensors
    These are used to measure acceleration forces and rotational forces along with three axes.
     
  2. Position Sensors
    These are used to measure the physical position of the device.
      
  3. Environmental Sensors
    These are used to measure environmental changes such as temperature, humidity etc.
Important points to remember-
 
Sensor Manager class
 
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
 
Sensor class
 
The android.hardware.Sensor class provides methods to get information about the sensor such as sensor name, sensor type, sensor resolution, sensor type etc.
 
Sensor Event class
 
Its instance is created by the system. It provides information about the sensor.
 
Sensor Event Listener interface
 
It provides two callback methods to get information when sensor values (x,y, and z) change or sensor accuracy changes.
 
S.I NO DESCRIPTION
1)   getDefaultSensor(int type) This method get the default sensor for a given type.  
2)   getOrientation(float[] R, float[] values) This method returns a description of the current primary clip on the clipboard but not a copy of its data.  
3)   unregisterListener(SensorEventListener listener, Sensor sensor) This method unregisters a listener for the sensors with which it is registered.  
4)   registerListener(SensorListener listener, int sensors, int rate) This method registers a listener for the sensor  
5)   getAltitude(float p0, float p) This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level.  
6)   getInclination(float[] I) This method computes the geomagnetic inclination angle in radians from the inclination matrix.  
7)   getOrientation(float[] R, float[] values) This method computes the device's orientation based on the rotation matrix.  
 
Create New Project
 
Open Android Studio and create a new Android Studio project.
 
Android
 
activity_main.xml
 
Go to activity_main.xml. This XML file contains the designing code for an Android app in the activity_main.xml.
 
Android
 
The XML code is given below
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context=".MainActivity" >  
  8.   
  9.     <TextView  
  10.         android:id="@+id/textView"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="match_parent"  
  13.         android:text="Shake to switch color" />  
  14.   
  15. </RelativeLayout>  
MainActivity.java
 
Go to  Main Activity.java. This Java program is the backend language for Android.
 
Android
 
The java code is given below.
  1. package abu.sensor;  
  2.   
  3. import android.app.Activity;  
  4. import android.graphics.Color;  
  5. import android.hardware.Sensor;  
  6. import android.hardware.SensorEvent;  
  7. import android.hardware.SensorEventListener;  
  8. import android.hardware.SensorManager;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.widget.Toast;  
  12.   
  13. public class MainActivity extends Activity implements SensorEventListener{  
  14.     private SensorManager sensorManager;  
  15.     private boolean isColor = false;  
  16.     private View view;  
  17.     private long lastUpdate;  
  18.   
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.         view = findViewById(R.id.textView);  
  24.         view.setBackgroundColor(Color.CYAN);  
  25.   
  26.         sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);  
  27.         lastUpdate = System.currentTimeMillis();  
  28.     }  
  29.   
  30.     @Override  
  31.     public void onAccuracyChanged(Sensor sensor, int accuracy) {}  
  32.     @Override  
  33.     public void onSensorChanged(SensorEvent event) {  
  34.         if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {  
  35.             getAccelerometer(event);  
  36.         }  
  37.   
  38.     }  
  39.   
  40.     private void getAccelerometer(SensorEvent event) {  
  41.         float[] values = event.values;  
  42.         // Movement  
  43.         float x = values[0];  
  44.         float y = values[1];  
  45.         float z = values[2];  
  46.   
  47.         float accelationSquareRoot = (x * x + y * y + z * z)  
  48.                 / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);  
  49.   
  50.         long actualTime = System.currentTimeMillis();  
  51.         Toast.makeText(getApplicationContext(),String.valueOf(accelationSquareRoot)+" "+  
  52.                 SensorManager.GRAVITY_EARTH,Toast.LENGTH_SHORT).show();  
  53.   
  54.         if (accelationSquareRoot >= 2)  
  55.         {  
  56.   
  57.             if (actualTime - lastUpdate < 200) {  
  58.                 return;  
  59.             }  
  60.             lastUpdate = actualTime;  
  61.               if (isColor) {  
  62.                 view.setBackgroundColor(Color.MAGENTA);  
  63.   
  64.             } else {  
  65.                 view.setBackgroundColor(Color.BLUE);  
  66.             }  
  67.             isColor = !isColor;  
  68.         }  
  69.   
  70.     }  
  71.   
  72.     @Override  
  73.     protected void onResume() {  
  74.         super.onResume();  
  75.   
  76.         sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),  
  77.                 SensorManager.SENSOR_DELAY_NORMAL);  
  78.     }  
  79.   
  80.     @Override  
  81.     protected void onPause() {  
  82.   
  83.         super.onPause();  
  84.         sensorManager.unregisterListener(this);  
  85.     }  
  86. }  
Debug The Error
 
Now, go to menu bar and click "make project" or press ctrl+f9 to debug the error.
 
Android
 
Run the project
 
Then, click the "Run" button or press shift+f10 to run the project. Choose the virtual machine and click OK.
 
Android
 

Conclusion

 
We have successfully created a Sensor Android application using Android Studio.
 
Android
 
Android
 
Android