Fundamentals
Introduction
1st Android Application

OOPS Concepts
Class
Object
Abstraction
Encapsulation

Polymorphism
Inheritance
Message Passing
Dynamic Binding

UI Controls
TextView
Button
Toggle Button
CheckBox
Radio Button
Spinner
ProgressBar
SeekBar
RadioGroup
RatingBar
Switch
EditText
AutoComplete
TextView

MultiAutoComplete
TextView

ImageView
ImageButton
Gallery
MediaPlayer
VideoView
MediaController

TimePicker
DatePicker
CalendarView
Chronometer
Analog Clock
Digital Clock

Layouts
LinearLayout
RelativeLayout
GridLayout
TableLayout
FrameLayout
Fragment

Composite
ListView
ExpandableListView
GridView
ScrollView
SearchView
Sliding Drawer
Tab Widget
WebView

Transitions
Image Switcher
StackView
TextSwitcher
ViewAnimator
View Flipper
View Switcher

Advanced
Request Focus
View
View Stub
TextureView
Gesture Overlay View

SurfaceView
NumberPicker
Zoom Button
Zoom Controls
AbsoluteLayout

Database
SharedPreference
SQLite DB
MySQL DB

Webservices
Check HttpURLConnection
Single Webservice Call
Multi Webservice Call
ListView from Webservice
SQLite from Webservice
Data from Database

Telephone Manager
IMEI
IMSI
Phone Type
Sim Type
Network Type

Content Providers
Contact Provider
BookMark Provider
Own Provider


Message & Networking
Send SMS
SMS with Reports
Group SMS

Send E-Mail
Download Binary Data


Location Based Service
Display Google Map
Events with Google Map

Android Services
Create Service
Create Longtime Service

Asynchronous Task
Repeating Services
IntentService

Activity from a Service
Bind Activity to Service


Sample Projects
HMS
CNB
Login Screen
Camera Event
Browse Option
QR Code Events
Accelerometer Sensor
EditText from Spinner

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








SHARE THIS PAGE



product 2

product 3

product 4

Feedbacks : balaji.scz@gmail.com