Android Motion Sensor using SensorManager and SensorEventListener

0
110

Hello Developers, In this tutorial, I will show you how you can use SensorManager and SensorEventListener class to implement Motion Sensor in your android application.We will create an application which will change the image when you shake your phone.

Motion Sensor is used to detect the changes (acceleration and rotational forces) in all the three-dimension.In this example, we will use SensorManager class which is used to access the phone’s sensors (here we will use accelerometer sensor) and is used to get the sensor service and sensor instance.

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

So, let’s get started –

1.Open Android Studio and create a new project ->name your project -> select target android version -> now click Empty Activity -> click finish. This creates basic android activity.

2.Now, Add images in your res/drawable folder which will be shown on your phone shake.

3. AndroidManifest.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.prateek.motionsensor">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4.Now, Open your activity_main.xml file-

In this file, we will have only two fields- TextView and ImageView(to display the images on phone shake).

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.prateek.motionsensor.MainActivity"
    android:background="#fae930">


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/kunfu"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.555"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.495" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Shake your phone to switch images"
        android:textColor="#000000"
        android:textSize="20sp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintBottom_toTopOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.296" />

</android.support.constraint.ConstraintLayout>

5. Now, Open the MainActivity.java file and make these changes –

package com.example.prateek.motionsensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    SensorManager sm;
    ImageView btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn =(ImageView) findViewById(R.id.imageView);
        sm=(SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
        
        sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy){}
    
    @Override
    public void onSensorChanged(SensorEvent event)
    {
        if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER)
        {
            float value[]=event.values;
            float x=value[0];
            float y=value[1];
            float z=value[2];
           
            float movement_shake=((x*x+y*y+z*z)/(SensorManager.GRAVITY_EARTH*
                    SensorManager.GRAVITY_EARTH));
            
            if(movement_shake>=2)
            {
                btn.setImageDrawable(getResources().getDrawable(R.drawable.kunfu2));
                Toast.makeText(this, "Shake detected", Toast.LENGTH_SHORT).show();
            }
            else
                {btn.setImageDrawable(getResources().getDrawable(R.drawable.kunfu));}
        }
    }
}

At first, we declare and initiate out ImageView and TextView for our Motion Sensor, then we get the instance of SensorManager by calling getSystemService() method and then passing the SENSOR_SERVICE constant in it.The registerListener() is called and the type of sensor to use and the delay of a sensor is given as parameter.

Related:

Handle on touch event on Google-Map in Android

How to use Event bus on Android

Android Real Time Face detection and Prediction using Google Mobile Vision API

Detecting Swipe Gestures Android Tutorial

Now, onAccuracyChanged(Sensor sensor, int accuracy) method is called when the accuracy of the registered sensor has changed.

Now, onSensorChanged(SensorEvent event) is called when there are a new sensor event and your phone moves in any direction.In this method, we use the values of motion change in all the direction and derive a value from the formula given in code using the motion of all the direction and SensorManager.GRAVITY_EARTH.

Now, If this value is significant (when the phone is shaken) then setImageDrawable() method is called and changes the image otherwise the previous image is shown. If You are Beginner Learn Android application development from the scratch

6.Now, finally run the application and this will be the result –


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Motion Sensor pic1

Motion Sensor pic2

LEAVE A REPLY

Please enter your comment!
Please enter your name here