Pages

Monday, 28 October 2013

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

19 comments:

  1. Sir, can you explain this part in detail:

    Random r=new Random();
    int i=r.nextInt(10);
    tv.setText(""+i);

    ReplyDelete
    Replies
    1. Random class is used to generate random number.
      detail line by line:
      1. Created object(r) of Random class
      2. generate random number from 0 to 9 and assign it into i integer
      3. display value of i on TextView

      setText is used to set text on TextView and it takes string to display, so i used double quoted with integer value.

      Delete
    2. how to render pdf in android i alredy done but i cant click any hyperlink in that page pls help meeeeeeee

      Delete
    3. @AJEENA if you are using text view than add it: android:autoLink="web"

      Delete
    4. This comment has been removed by the author.

      Delete
  2. any idea about killing all process android in backgorund programmatically..Your help will b appericiated

    ReplyDelete
  3. sir .. y we take asr as float value n what it means n y we used that formula for asr why not other ,...

    ReplyDelete
  4. Hi,
    Can anyone tell me how do i increase the threshold value of shake.

    ReplyDelete
  5. Anonymous12:51 pm

    This comment has been removed by the author.

    ReplyDelete
  6. Anonymous12:52 pm

    In which software i can run the program

    ReplyDelete
    Replies
    1. Generate apk and install in any android device.

      Delete
  7. Not working. Help please

    ReplyDelete
  8. Sir can you help with codes for android offline voice command recognition
    Thanks

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. It's not working for me.
    It's not showing the count.
    Can you tell me why it is so?

    ReplyDelete
  11. sir i written the code in android studio but it gives the error when i write @override and then start onAccuracyChanged method and also on onSensorChanged. plz help out me in this problem

    ReplyDelete
  12. it gives error on astudio 13line

    ReplyDelete
  13. nexpected error while executing: am start -n "com.example.anmol.motion_sensor/com.example.anmol.motion_sensor.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
    i found this error

    ReplyDelete

Back to Top