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:
<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
Nice Post
ReplyDeleteSir, can you explain this part in detail:
ReplyDeleteRandom r=new Random();
int i=r.nextInt(10);
tv.setText(""+i);
Random class is used to generate random number.
Deletedetail 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.
how to render pdf in android i alredy done but i cant click any hyperlink in that page pls help meeeeeeee
Delete@AJEENA if you are using text view than add it: android:autoLink="web"
DeleteThis comment has been removed by the author.
Deleteany idea about killing all process android in backgorund programmatically..Your help will b appericiated
ReplyDeletesir .. y we take asr as float value n what it means n y we used that formula for asr why not other ,...
ReplyDeleteHi,
ReplyDeleteCan anyone tell me how do i increase the threshold value of shake.
This comment has been removed by the author.
ReplyDeleteIn which software i can run the program
ReplyDeleteGenerate apk and install in any android device.
DeleteNot working. Help please
ReplyDeleteSir can you help with codes for android offline voice command recognition
ReplyDeleteThanks
This comment has been removed by the author.
ReplyDeleteIt's not working for me.
ReplyDeleteIt's not showing the count.
Can you tell me why it is so?
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
ReplyDeleteit gives error on astudio 13line
ReplyDeletenexpected 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
ReplyDeletei found this error