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,
- Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
- Position Sensors
These are used to measure the physical position of the device.
- Environmental Sensors
These are used to measure the 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 of 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.
activity_main.xml
Go to activity_main.xml. This XML file contains the designing code for an Android app in the activity_main.xml.
The XML code is given below
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- 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="match_parent"
- android:layout_height="match_parent"
- android:text="Shake to switch color" />
-
- </RelativeLayout>
MainActivity.java
Go to Main Activity.java. This Java program is the backend language for Android.
The java code is given below.
- package abu.sensor;
-
- import android.app.Activity;
- 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.view.View;
- import android.widget.Toast;
-
- public class MainActivity extends Activity implements SensorEventListener{
- private SensorManager sensorManager;
- private boolean isColor = false;
- private View view;
- private long lastUpdate;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- view = findViewById(R.id.textView);
- view.setBackgroundColor(Color.CYAN);
-
- sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
- lastUpdate = System.currentTimeMillis();
- }
-
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {}
- @Override
- public void onSensorChanged(SensorEvent event) {
- if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
- getAccelerometer(event);
- }
-
- }
-
- private void getAccelerometer(SensorEvent event) {
- float[] values = event.values;
-
- float x = values[0];
- float y = values[1];
- float z = values[2];
-
- float accelationSquareRoot = (x * x + y * y + z * z)
- / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
-
- long actualTime = System.currentTimeMillis();
- Toast.makeText(getApplicationContext(),String.valueOf(accelationSquareRoot)+" "+
- SensorManager.GRAVITY_EARTH,Toast.LENGTH_SHORT).show();
-
- if (accelationSquareRoot >= 2)
- {
-
- if (actualTime - lastUpdate < 200) {
- return;
- }
- lastUpdate = actualTime;
- if (isColor) {
- view.setBackgroundColor(Color.MAGENTA);
-
- } else {
- view.setBackgroundColor(Color.BLUE);
- }
- isColor = !isColor;
- }
-
- }
-
- @Override
- protected void onResume() {
- super.onResume();
-
- sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
- SensorManager.SENSOR_DELAY_NORMAL);
- }
-
- @Override
- protected void onPause() {
-
- super.onPause();
- sensorManager.unregisterListener(this);
- }
- }
Debug The Error
Now, go to menu bar and click "make project" or press ctrl+f9 to debug the error.
Run the project
Then, click "Run" button or press shift+f10 to run the project. Choose the virtual machine and click OK.
Conclusion
We have successfully created a Sensor Android application using Android Studio.