Introduction
Sensor Manager is used to manage the Sensor in Android with our app. Sensors are essential components in android used to automatically change the state by user condition. As we are using many sensors in our mobile like the Proximity sensor (whenever we receive a call it automatically turns off the screen) and accelerator sensor (to move the phone from vertical to horizontal it automatically changes the orientation of the app or mobile).
Types of Sensors
- SENSOR_PROXIMITY
- SENSOR_ACCELEROMETER
- SENSOR_LIGHT
- SENSOR_STATUS_ACCURACY_HIGH
- SENSOR_STATUS_ACCURACY_LOW
And many more are available in the Android Documentation you can refer to that. Sensors are used in various approaches, to use any sensor we follow the following process.
How to use Sensor?
There are two important things to remember before using the Sensor in our android app these are as following
- Sensor Manager - Sensor manager access system or os via
sensorManager.getDefaultSensor()
method, which takes the sensor type and the delay defined as constants on SensorManager
as parameters
- Sensor Listener - Once the sensor is initialized Sensor must be registered using
SensorManager.registerListener,
and then it implements SensorEvent listener to override its two methods.
Now to use Sensor in our app we go through following steps-
- Delcare Sensor Manager and Sensor.
- Initialize that Sensor Manager and Sensor.
- Checking the Sensor is available in the device or not and registering Sensor Manager
- Implement the SensorEventListener and its methods
- Unregister and re-register the Sensor Manager according to usability.
Example of Sensor app
Here we make a very simple app for proximity Sensor that will Sensor the palm or any motion things to be near or in distance.
Step 1
Here we have declared the Sensor Manager, proximity sensor, and textview.
SensorManager sensorManager;
Sensor ProximitySensor;
TextView tv1;
Step 2
Next, we initialize the textview, Sensor manager, and Proximity Sensor.
tv1 = findViewById(R.id.textview);
tv1.setBackgroundColor(Color.YELLOW);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
ProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
Now we check whether the Proximity Sensor exists in our Mobile phone Device or not. if exists we register the Sensor Manager
Step 3
if (ProximitySensor == null) {
Toast.makeText(this, "No proximity sensor found in device.", Toast.LENGTH_SHORT).show();
finish();
} else {
// registering our sensor with sensor manager.
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL);
}
Next, we move to the MainActivity class and implement the SensorEventListener class and override two methods by clicking on an error on the side panel.
public class MainActivity extends AppCompatActivity implements SensorEventListener {--}
The two methods are onSensorChanged() and onAccuracyChanged().
In onSensorChanged() methods we compare the value of sensor (0 - sensor off, 1 - sensor on) and according to the value we set the text in our TextView.
Step 4
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
// getproximity(sensorEvent);
//}
if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if (sensorEvent.values[0] == 0) {
// here we are setting our status to our textview..
// if sensor event return 0 then object is closed
// to sensor else object is away from sensor.
tv1.setText("Near");
} else {
tv1.setText("Away");
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {}
Leaving Sensor On can drain the device battery and use the resource that is neither used in the background so we have to unregister the listener of Sensor Manager on onPause() method and resume or re-register the Sensor Manager on onResume() method. Hence we will do that task using following code.
Step 5
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
Full Code Snippet
activityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.sensor_manager_ex2;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
SensorManager sensorManager;
Sensor ProximitySensor;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = findViewById(R.id.textview);
tv1.setBackgroundColor(Color.YELLOW);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
ProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (ProximitySensor == null) {
Toast.makeText(this, "No proximity sensor found in device.", Toast.LENGTH_SHORT).show();
finish();
} else {
// registering our sensor with sensor manager.
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL);
}
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
// if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
// getproximity(sensorEvent);
// }
if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if (sensorEvent.values[0] == 0) {
// here we are setting our status to our textview..
// if sensor event return 0 then object is closed
// to sensor else object is away from sensor.
tv1.setText("Near");
} else {
tv1.setText("Away");
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
Output
When an object like our palm reaches the sensor near the phone microphone the app text will convert into Near and after removing the object it again set to Away.
Conclusion
Here in this article, we have discussed what is Sensors and what are the different types of sensors in Android, how to use Sensors in our app, and also illustrated using sensors with an example of a Proximity Sensor.