android app development

Accelerometer Sensor in Android Studio

Accelerometer Sensor Application Development:

Accelerometer Sensor in android Studio- in this article, I am going to show you how to use the accelerometer sensor, I believe you must have learned the concept of acceleration before in physics class. It is used to describe the motion of objects. The physical quantity of the speed change, in m/s2. The accelerometer sensor in Android provides a mechanism, Allows us to obtain the current acceleration information of the mobile phone in the application, and use this information to develop some fun features.


How to use the accelerometer sensor in Android:

As mentioned earlier, the usage of each sensor is similar. In the previous Article, you have already mastered the light According to the usage of the sensor, therefore, we will not introduce the repetitive part here. When using the accelerometer sensor, only Two things need to be noted. First, when obtaining the Sensor instance, you must specify an acceleration sensor constant, as shown below:

Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

Second, the information output by the accelerometer sensor in android is also stored in the values ​​array of SensorEvent.

There will be three values ​​in the values ​​array at this time, which represent the acceleration information of the phone in the X-axis, Y-axis and Z-axis directions.

The meaning of X axis, Y axis and Z axis in the space coordinate system is shown in below Figure.

accelerometer sensor in android

It should be noted that due to the existence of gravity, your mobile phone will have a gravity no matter where it is in the world.

Acceleration, the value of this acceleration is about 9.8m/s2. When the phone is placed horizontally, this acceleration is acting on the Z-axis Yes, when the phone is upright, this acceleration is acting on the Y axis. When the phone is upright, this acceleration is acting on the X axis.



Create Shaking application like Viber and WeChat:

Next, we try to use shake function using accelerometer sensor to make application like WeChat and viber. In fact, the main logic is also very Simple, only need to detect the acceleration of the mobile phone on the X-axis, Y-axis and Z-axis, when the predetermined value is reached, it can be considered The user shakes the phone, which triggers the shaking logic. Now the question is, how much should this predetermined value be set to? Due to the existence of gravitational acceleration, even when the mobile phone is stationary, the acceleration on a certain axis may reach 9.8m/s2, so this predetermined value must be greater than 9.8m/s2, here we set it to 15m/s2.

Create a new project

accelerometer sensor in android


Select empty activity and press the next button.

accelerometer sensor in android

Set the application name in my case I set the name “AccelerometerSensorDemo”, and press the finish button.

accelerometer sensor in android


Accelerometer sensor in android Programming:

Java Code:

 modify the code in MainActivity.java as follows:

package com.example.accelerometersensordemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private SensorManager sensorManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sensorManager != null) {
            sensorManager.unregisterListener(listener);
        }
    }
    private SensorEventListener listener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
// The acceleration may be negative, so take their absolute value
            float xValue = Math.abs(event.values[0]);
            float yValue = Math.abs(event.values[1]);
            float zValue = Math.abs(event.values[2]);
            if (xValue > 15 || yValue > 15 || zValue > 15) {
// message for user
                Toast.makeText(MainActivity.this, "shake function activated", Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };
}


Program explanation:

As you can see, this example is still very simple. We get X in the onSensorChanged() method. Axis, Y-axis and Z-axis direction acceleration value, and because the acceleration may be negative, so here is the obtained The data has been processed in absolute value. Next, a simple judgment is made. If the phone is on the X-axis or Y-axis or Z-axis If the upward acceleration value is greater than 15m/s2, it is considered that the user has shaken the phone, which triggers the shaking logic. Of course here For the sake of simplicity, we just popped up a Toast.

XML Code:

modify the code in activity_main.xml as follows:

<?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">



</RelativeLayout>

Now run the program and shake your phone, you will see a Toast prompt as you can see in the below video. this program is just a very, very simple example. You can also optimize it in many ways. For example, control the trigger frequency of shaking so that it cannot be triggered twice in a short time. More rigorous logic depends on you Improve it by yourself.



Accelerometer Sensor Application Testing:

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button