Tuesday 15 October 2013

On Launch

Android Sensor Accelerometer

On Shake changes Background

Android Sensor Accelerometer

Create new Android Project
Project Name: Accelerometer
//tested from 2.3.3 to current android sdk 
Build Target: Android 2.3.3   //or greater than that
Application Name: Accelerometer
Package Name: com.shaikhhamadali.blogspot.accelerometer
Create layout file: activity_accelerometer


  1. create layout: 

<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"
    android:id="@+id/rL_Accelerometer"
    tools:context=".Accelerometer" >

    <TextView
        android:id="@+id/tVChangeBG"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Shake to change background"
        android:textColor="#000025"
        android:textSize="30sp" />

</RelativeLayout>

2.code of activity:

package com.shaikhhamadali.blogspot.accelerometer;

import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class Accelerometer extends Activity implements SensorEventListener {
 //SensorManager lets you access the device's sensors
 //declare Variables
 private SensorManager sensorManager;
 private boolean color = false;
 private long lastUpdate;
 RelativeLayout rL_Accelerometer;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  //Hide Navigation and make this full screen
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_accelerometer);
  //Create instance of Layout
  rL_Accelerometer= (RelativeLayout)findViewById(R.id.rL_Accelerometer);
  //change background color 1st
  rL_Accelerometer.setBackgroundColor(Color.GREEN);
  //create instance of sensor manager and get system service to interact with Sensor
  sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  lastUpdate = System.currentTimeMillis();
 }
 // called when sensor value have changed
 @Override
 public void onSensorChanged(SensorEvent event) {
  if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
   getAccelerometer(event);
  }

 }

 private void getAccelerometer(SensorEvent event) {
  float[] values = event.values;
  // Movement
  float x = values[0];
  float y = values[1];
  float z = values[2];
  //get acceleration 
  float accelationSquareRoot = (x * x + y * y + z * z)
    / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
  //get current time
  long actualTime = System.currentTimeMillis();
  if (accelationSquareRoot >= 2)
  {
   if (actualTime - lastUpdate < 200) {
    return;
   }
   lastUpdate = actualTime;
   Toast.makeText(this, "Device was shaked", Toast.LENGTH_SHORT)
   .show();
   if (color) {
    rL_Accelerometer.setBackgroundColor(Color.YELLOW);

   } else {
    rL_Accelerometer.setBackgroundColor(Color.BLUE);
   }
   color = !color;
  }
 }

 @Override
 public void onAccuracyChanged(Sensor sensor, int accuracy) {

 }

 @Override
 protected void onResume() {
  super.onResume();
  // register this class as a listener for the orientation and
  // accelerometer sensors
  sensorManager.registerListener(this,
    sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
    SensorManager.SENSOR_DELAY_NORMAL);
 }

 @Override
 protected void onPause() {
  // unregister listener
  super.onPause();
  sensorManager.unregisterListener(this);
 }
} 

3. note that:

  • you can use Accelerometer to change background color,change date,update status etc
  • must unregister Sensor on pause and register on resume.
  • Learn more about Sensors and multiple types of sensors.

4. conclusion:

  • Some information about how to use Accelerometer.
  • know what are Sensors and how to use Sensors.

5. About the post:

  • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
  •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
  •  Hope you enjoy it!
6. Source Code:
        you can download the source code here

Cheers,
Hamad Ali Shaikh