Motion detection using Sensor in Android


In this application, we will learn how to use Sensor and how to perform action if we shake device in any direction. There are many sensors available in mobile devices but usually all mobile device have Accelerometer sensor and this sensor is used to catch motion of the device. So we can easily find direction in which mobile is moving. So let’s start to get direction of the mobile motion, create new project and drop one text view and give id textView1 which will use to display random number on every shake of mobile in any direction. The code of android XML file is given below:

Android Sensor ExampleMotion detection using Sensor in Android
<LinearLayout 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"
   android:background="#d56"
   android:orientation="vertical" >

<TextView
   android:id="@+id/textView1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:text=""
   android:gravity="center"
   android:textSize="400sp" />
</LinearLayout>

Now open your Java file and use Sensor manager to get sensor services. Register your Sensor object to Accelerometer sensor and give delay according to your application, use game delay in game application. Now whenever we shake our mobile device in any direction than onSensorChanged() method will call and object of SensorEvent will keep the new direction (axis) values (i.e. x, y and z). Now take these values and use in any action, we can perform different action on every different axis, but here we are using all values and performing an action if device shakes in any direction. The code of android Java file is given below with explanation:

package sense.nonsense; //your package name

import java.util.Random;
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.app.Activity;
import android.content.Context;

public class MainActivity extends Activity implements SensorEventListener {
  SensorManager sm;
  TextView tv;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   tv=(TextView)findViewById(R.id.textView1);
   //get sensor service
   sm=(SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
   //Tell which sensor you are going to use
   //And declare delay of sensor
   //Register all to your sensor object to use
 sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy)
  {
   // TODO Auto-generated method stub
  }
  //This method is called when your mobile moves any direction
  @Override
  public void onSensorChanged(SensorEvent event)
  {
   if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER)
   {
    //get x, y, z values
    float value[]=event.values;
    float x=value[0];
    float y=value[1];
    float z=value[2];
    //use the following formula
   //use gravity according to your place if you are on moon than use moon gravity
   float asr=(x*x+y*y+z*z)/(SensorManager.GRAVITY_EARTH*
SensorManager.GRAVITY_EARTH);
   //If mobile move any direction then the following condition will become true
   if(asr>=2)
     {
      //Generate random number every time and display on text view
      Random r=new Random();
      int i=r.nextInt(10);
      tv.setText(""+i);
     }
    }
  }
}
 

Now run your project and install .apk file in your mobile and test. You can’t test it on emulator because you can’t shake your emulator and there is no sensor in emulator. If you have any doubts please comment.

Related Tutorials:-

★ Convert Text to Speech

★ Use Shared Preferences

★ Perform action on any Hardware button

★ Get all Mobile Contacts

★ Get Battery level using Broadcast Receiver

Anúncios

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s