Friday, 30 January 2015

Android Sensor Example

Sensors can be used to monitor the three-dimensional device movement or change in the environment of the device.
Types Of Sensors
Android supports three types of sensors:

Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
Motion sensors that are supported on the Android platform.
1.TYPE_ACCELEROMETER
2.TYPE_GRAVITY
3.TYPE_GYROSCOPE
4.TYPE_GYROSCOPE_UNCALIBRATED
5.TYPE_LINEAR_ACCELERATION
6.TYPE_ROTATION_VECTOR
7.TYPE_SIGNIFICANT_MOTION
8.TYPE_STEP_COUNTER
9.TYPE_STEP_DETECTOR

 Position Sensors
These are used to measure the physical position of device.
Position sensors that are supported on the Android platform.
1.TYPE_GAME_ROTATION_VECTOR
2.TYPE_GEOMAGNETIC_ROTATION_VECTOR
3.TYPE_MAGNETIC_FIELD
4.TYPE_MAGNETIC_FIELD_UNCALIBRATED
5.TYPE_ORIENTATION
6.TYPE_PROXIMITY

Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
Environment sensors that are supported on the Android platform.
1.TYPE_AMBIENT_TEMPERATURE
2.TYPE_LIGHT
3.TYPE_PRESSURE
4.TYPE_TEMPERATURE
5.TYPE_RELATIVE_HUMIDITY

Android Sensor
Example:

MainActivity.java

import java.util.List;
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.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  implements SensorEventListener{
private SensorManager sensorManager;
private boolean isColor = false;  
private View view;  
 private long lastUpdate;  
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView sensorsData = (TextView)findViewById(R.id.textView1);
view = findViewById(R.id.textView2);  
view.setBackgroundColor(Color.GREEN);  
sensorManager = (SensorManager)this.getSystemService(SENSOR_SERVICE);
 /*SENSOR LIST*/
 List<Sensor> list = sensorManager.getSensorList(Sensor.TYPE_ALL);
 StringBuilder data = new StringBuilder();
data.append("Types Of Sensors:\n\n");
 for(Sensor sensor:list){
 data.append(sensor.getName() + "\n\n");
// data.append(sensor.getVendor() + "\n");
 // data.append(sensor.getVersion() + "\n");            
 }
 sensorsData.setText(data);
 /*Shaking Sensor*/
  lastUpdate = System.currentTimeMillis();  
}

//overriding two methods of SensorEventListener  
 @Override  
 public void onAccuracyChanged(Sensor sensor, int accuracy) {}  
 @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];  
      float accelationSquareRoot = (x * x + y * y + z * z)  
          / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);  
      
      long actualTime = System.currentTimeMillis();  
      Toast.makeText(getApplicationContext(),String.valueOf(accelationSquareRoot)+" "+  
                  SensorManager.GRAVITY_EARTH,Toast.LENGTH_SHORT).show();  
        
      if (accelationSquareRoot >= 2) //it will be executed if you shuffle  
      {  
          
        if (actualTime - lastUpdate < 200) {  
          return;  
        }  
        lastUpdate = actualTime;//updating lastUpdate for next shuffle  
         if (isColor) {  
          view.setBackgroundColor(Color.GREEN);  

        } else {  
          view.setBackgroundColor(Color.RED);  
        }  
        isColor = !isColor;  
      }  
    }  

    @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_ACC     ELEROMETER),  
    SensorManager.SENSOR_DELAY_NORMAL);  
    }  

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

}

activity_main.xml:

<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:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <ScrollView
      android:id="@+id/scrollView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true" >

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

 <TextView
     android:id="@+id/textView2"
     android:layout_width="wrap_content"
     android:layout_height="57dp"
     android:text="Shake to switch color"
     android:textAppearance="?android:attr/textAppearanceLarge" />

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:textColor="#29166f"
      android:textAppearance="?android:attr/textAppearanceMedium" />

      </LinearLayout>
   </ScrollView>

</RelativeLayout>

Output:

No comments:

Post a Comment