Skip to main content

Android Accelerometer Sensor

  1. Get X, Y & Z Direction through Accelerometer in Android
  2. Create Accelerometer Sensor Event in Android
  3. Shake to call Next Page Activity in Android

Note                     Download ADT Plugin Here.
Here I am using,
OS : Linux (Ubuntu 12.04)
Eclipse : Juno (Version 4.2.0)
Android API Level : 3 to 'n' as per need
Emulator API Level : It will be displayed in output image 

A. Get X, Y & Z Direction through Accelerometer in Android

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:textSize="25sp"
        android:textColor="#4169E1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="65dp"
        android:text="Accelerometer" />
 
    <TextView
        android:id="@+id/textView2"
        android:textSize="18sp"
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView3"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="30dp"
        android:text="X Value" />
 
    <TextView
        android:id="@+id/textView3"
        android:textSize="18sp"
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Y Value" />
 
    <TextView
        android:id="@+id/textView4"
        android:textSize="18sp"
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="30dp"
        android:text="Z Value" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.accelerometer_ex1;
 
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.view.Menu;
import android.widget.TextView;
 
public class MainActivity extends Activity implements SensorEventListener {
 
 private SensorManager sensorManager;
 
 TextView x;
 TextView y;
 TextView z;
 
 String sx, sy, sz;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  x = (TextView) findViewById (R.id.textView2);
  y = (TextView) findViewById (R.id.textView3);
  z = (TextView) findViewById (R.id.textView4);
  
  sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  
  sensorManager.registerListener(this, sensorManager.getDefaultSensor
    (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
 
 @Override
 public void onAccuracyChanged(Sensor arg0, int arg1) {
  // TODO Auto-generated method stub
  
 }
 
 @Override
 public void onSensorChanged(SensorEvent event) {
  // TODO Auto-generated method stub
  
  if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
   
   float xVal = event.values[0];
   float yVal = event.values[1];
   float zVal = event.values[2];
   
   sx = "X Value : <font color = '#800080'> " + xVal + "</font>";
   sy = "Y Value : <font color = '#800080'> " + yVal + "</font>";
   sz = "Z Value : <font color = '#800080'> " + zVal + "</font>";
   
   x.setText(Html.fromHtml(sx));
   y.setText(Html.fromHtml(sy));
   z.setText(Html.fromHtml(sz));
  }
 }
}

Step 4 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.accelerometer_ex1"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="balaji.accelerometer_ex1.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">Accelerometer_Ex1</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
 
</resources>

Step 6 : Our output will be like this :


Output

Run this Program in Real Device







B. Create Accelerometer Sensor Event in Android

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<RelativeLayout 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"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:textSize="25sp"
        android:textColor="#4169E1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="Accelerometer - Shake" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.accelerometer_ex2;
 
import android.app.Activity;
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.widget.Toast;
 
public class MainActivity extends Activity implements SensorEventListener {
 
 SensorManager sm;
 TextView text;
 long lastUpdate;
  
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  text = (TextView) findViewById(R.id.textView1);
 
  sm = (SensorManager) getSystemService(SENSOR_SERVICE);
  lastUpdate = System.currentTimeMillis();
 }
 
 @Override
 public void onSensorChanged(SensorEvent event) {
  
  if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
   
   getAccelerometer(event);
  }
 }
 
 private void getAccelerometer(SensorEvent event) {
  
  float[] values = event.values;
 
  float x = values[0];
  float y = values[1];
  float z = values[2];
 
  float accelationSquareRoot = (x*x + y*y + z*z)
    / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
  
  long actualTime = System.currentTimeMillis();
  
  if (accelationSquareRoot >= 2) {
   
   if (actualTime-lastUpdate < 200) {
    
    return;
   }
   
   lastUpdate = actualTime;
   
   // Perform your Action Here..
   
   Toast.makeText(this, "Device was shuffled",
     Toast.LENGTH_SHORT).show();
  }
 }
 
 @Override
 public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
 }
 
 @Override
 protected void onPause() {
  // unregister listener
  super.onPause();
  sm.unregisterListener(this);
 }
 
 @Override
 protected void onResume() {
   
  super.onResume();
  sm.registerListener(this, sm.getDefaultSensor
    (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
 }
} 

Step 4 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.accelerometer_ex2"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="balaji.accelerometer_ex2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">Accelerometer</string>
    <string name="menu_settings">Settings</string>
 
</resources>

Step 6 : Our output will be like this :


Output

Run this Program in Real Device






Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!