Showing posts with label sensors. Show all posts
Showing posts with label sensors. Show all posts

Friday, 7 February 2014

Gravity Sensor Details

Gravity Sensor:

Gravity Sensor is a unique feature that allows applications to take advantage of the phone's real-world physical position in your hand.Also the Gravity sensor is the ability to play games without using your fingers and u can also move it side to side and it fit to the screen.And programmatically The gravity sensor provides a three dimensional vector indicating the direction and magnitude of gravity.

List of Gravity Sensors and Dialog

gravity Sensor detailsgravity Sensor details



Create new Android Project
Project Name: SensorDetails
//tested from 2.3.3 to current android sdk 
Build Target: Android 2.3.3   //or greater than that
Application Name: Sensor Details
Package Name: com.shaikhhamadali.blogspot.sensordetails
Create Activity file: SensorDetails


1.code of activity:


package com.shaikhhamadali.blogspot.sensordetails;

import java.util.List;

import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;

public class SensorDetails extends ListActivity {
 //declare Variables
 //SensorManager lets you access the device's sensors

 private SensorManager mySensorManager;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //create instance of sensor manager and get system service to interact with Sensor
  mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
  //Check the availability of sensor
  if (mySensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) != null){
   //create instance of List and get Gravity Sensor from Sensor Manager 
   List<Sensor> gravitySensorList = mySensorManager.getSensorList(Sensor.TYPE_GRAVITY);
   //Set ListAdapter of Sensor  
   setListAdapter(new ArrayAdapter<Sensor>(this,android.R.layout.simple_list_item_1,gravitySensorList));
  }else{
   //if Sensor Not found show Toast
   Toast.makeText(getApplicationContext(), "No Gravity Sensor!", Toast.LENGTH_LONG).show();
  }
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  //Get position of item click and create instance of sensor 
  Sensor sensor = (Sensor)l.getItemAtPosition(position);
  //Create instance of Alert dialog 
  AlertDialog.Builder sensorDialog = new AlertDialog.Builder(SensorDetails.this);
  //set title
  sensorDialog.setTitle(sensor.getName());

  @SuppressWarnings("unchecked")
  //create instance of class and get Sensor class
  Class<Sensor> sensorClass = (Class<Sensor>)sensor.getClass();
  //get details of sensor like Vendor, Version Type etc
  String vendor = sensor.getVendor();
  int version = sensor.getVersion();
  int type = sensor.getType();
  int minDelay = sensor.getMinDelay();
  float power = sensor.getPower();
  float maxRange = sensor.getMaximumRange();
  float resolution = sensor.getResolution();
  //Create instance of LinearLayout for alert dialog
  LinearLayout dialogLayout = new LinearLayout(getApplicationContext());
  dialogLayout.setBackgroundColor(Color.BLACK);
  //Create instance of Layout Params Width match parent and Height wrap content
  LayoutParams dialogLayoutParams = new LayoutParams(
    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
  //Set layout params to LinearLayout
  dialogLayout.setLayoutParams(dialogLayoutParams);
  //Set Orientation of Layout as Vertical
  dialogLayout.setOrientation(LinearLayout.VERTICAL);
  //Create Controls to add in Linear Layout and show details of Sensor  
  TextView textSensorClass = new TextView(getApplicationContext());
  textSensorClass.setText(sensorClass.toString());
  TextView textVendor = new TextView(getApplicationContext());
  textVendor.setText("Vendor: " + vendor);
  TextView textVersion = new TextView(getApplicationContext());
  textVersion.setText("Version: " + String.valueOf(version));
  TextView textType = new TextView(getApplicationContext());
  textType.setText("Type: " + String.valueOf(type));
  TextView textMinDelay = new TextView(getApplicationContext());
  textMinDelay.setText("MinDelay: " + String.valueOf(minDelay) + " microsecond");
  TextView textPower = new TextView(getApplicationContext());
  textPower.setText("Power: " + String.valueOf(power) + " mA");
  TextView textMaxRange = new TextView(getApplicationContext());
  textMaxRange.setText("MaximumRange: " + String.valueOf(maxRange));
  TextView textResolution = new TextView(getApplicationContext());
  textResolution.setText("Resolution: " + String.valueOf(resolution));
  //Add Views in Linear Layout
  dialogLayout.addView(textSensorClass);
  dialogLayout.addView(textVendor);
  dialogLayout.addView(textVersion);
  dialogLayout.addView(textType);
  dialogLayout.addView(textMinDelay);
  dialogLayout.addView(textPower);
  dialogLayout.addView(textMaxRange);
  dialogLayout.addView(textResolution);
  //Create Instance of ScrollView 
  ScrollView scrollView = new ScrollView(getApplicationContext());
  // Set Layout Params of ScrollView width match parent and height warp content
  LayoutParams scrollViewLayoutParams = new LayoutParams(
    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
  //Set Layout Params
  scrollView.setLayoutParams(scrollViewLayoutParams);
  //Add LAyout in ScrollView
  scrollView.addView(dialogLayout);
  //Set View on Dialog as ScrollView
  sensorDialog.setView(scrollView);
  //Show Dialog
  sensorDialog.show();
 }

}

2. note that:

  • you can use SensorManager to find out the available sensors in device and also selected type sensors as I use Gravity Sensor.
  • You can get all the details from Sensors as I use Gravity Sensor  
  • Learn more about Sensors and multiple types of sensors.

      3. conclusion:

      • Some information about how to get Description list of device Sensors.
      • know what are Sensors and how to use Sensors.
      • Know how to Create Alert Dialog with Dynamic Layout.

        4. 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!
            5. Source Code:
                    you can download the source code GoogleDrive, Github

            Cheers,
            Hamad Ali Shaikh

            Tuesday, 5 November 2013

            compass with accelerometer and magnetic sensor

            Compas

            compass outputcompass with accelerometer and magnetic sensor

            Create new Android ProjectProject Name: Compas//tested from 2.3.3 to current android sdk
            Build Target: Android 2.3.3 //or greater than thatApplication Name: CompasPackage Name: com.shaikhhamadali.blogspot.compasCreate activity file: Compas

            1.code of activity:

            package com.shaikhhamadali.blogspot.compass;
            import android.app.Activity;
            import android.content.Context;
            import android.graphics.Canvas;
            import android.graphics.Paint;
            import android.graphics.Paint.Style;
            import android.hardware.Sensor;
            import android.hardware.SensorEvent;
            import android.hardware.SensorEventListener;
            import android.hardware.SensorManager;
            import android.os.Bundle;
            import android.view.View;
            
            public class Compas extends Activity implements SensorEventListener {
             //declare Variables
             Float azimut;  
             CustomDrawableView mCustomDrawableView;// View to draw a compass
             //SensorManager lets you access the device's sensors
             private SensorManager mSensorManager;
             Sensor accelerometer;
             Sensor magnetometer;
            
             public class CustomDrawableView extends View {
              Paint paint = new Paint();
              public CustomDrawableView(Context context) {
               super(context);
               //color
               paint.setColor(0xff00ff00);
               //style 
               paint.setStyle(Style.STROKE);
               //stroke width
               paint.setStrokeWidth(2);
               //antiAlias
               paint.setAntiAlias(true);
               //text size
               paint.setTextSize(30);
              };
            
              protected void onDraw(Canvas canvas) {
               //declare Local Variables     
               int width = getWidth();
               int height = getHeight();
               int centerx = width/2;
               int centery = height/2;
               // Rotate the canvas with the azimut      
               if (azimut != null)
                //Preconcat the current matrix with the specified rotation.
                canvas.rotate(-azimut*360/(2*3.14159f), centerx, centery);
               //set color
               paint.setColor(0xff0000ff);
               //draw two lines
               canvas.drawLine(centerx, -1000, centerx, +1000, paint);
               canvas.drawLine(-1000, centery, 1000, centery, paint);
               //E,W,N,S directions
               canvas.drawText("N", centerx+15, centery-220, paint);
               canvas.drawText("S", centerx-30, centery+225, paint);
               canvas.drawText("E", centerx+215, centery-20, paint);
               canvas.drawText("W", centerx-220, centery+35, paint);
              }
             }
            
            
            
             protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              mCustomDrawableView = new CustomDrawableView(this);
              setContentView(mCustomDrawableView);    
              //create instance of sensor manager and get system service to interact with Sensor
            
              mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
              accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
              magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
             }
            
             protected void onResume() {
              super.onResume();
              // Register the sensor listeners
              mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
              mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
             }
            
             protected void onPause() {
              super.onPause();
              // unRegister the sensor listeners
              mSensorManager.unregisterListener(this);
             }
            
             public void onAccuracyChanged(Sensor sensor, int accuracy) {  }
            
             float[] mGravity;
             float[] mGeomagnetic;
             public void onSensorChanged(SensorEvent event) {
              if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
               mGravity = event.values;
              if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
               mGeomagnetic = event.values;
              if (mGravity != null && mGeomagnetic != null) {
               float R[] = new float[9];
               float I[] = new float[9];
               /*Computes the inclination matrix I as well as the rotation matrix R transforming a vector from the device coordinate
                *  system to the world's coordinate system which is defined as a direct orthonormal basis*/
               boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
               if (success) {
                float orientation[] = new float[3];
                /*Computes the device's orientation based on the rotation matrix*/
                SensorManager.getOrientation(R, orientation);
                azimut = orientation[0]; // orientation contains: azimut, pitch and roll
               }
              }
              mCustomDrawableView.invalidate();
             }
            }
            

            3. note that:

            4. conclusion:
            • Some information about how to use TYPE_MAGNETIC and TYPE_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 GoogleDrive, Github

            Cheers,
            Hamad Ali Shaikh

            Monday, 28 October 2013

            No object Near

            Android Sensor (Proximity Sensor)

            Near Object (near Ear while calling)

            Android Sensor (Proximity Sensor)


            Create new Android Project
            Project Name: ProximitySensor
            //tested from 2.3.3 to current android sdk 
            Build Target: Android 2.3.3   //or greater than that
            Application Name: Proximity Sensor
            Package Name: com.shaikhhamadali.blogspot.proximitysensor
            Create layout file: activity_proximity_sensor

            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"
                tools:context=".ProximitySensor" >
            
                <TextView
                    android:id="@+id/TextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="50dp"
                    android:text="Proximity Sensor"
                    android:textColor="#357345"
                    android:textSize="30sp" />
             <TextView 
                android:id="@+id/tVProximity"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/TextView"
                android:layout_marginTop="10dp"
                android:textSize="20sp"
                />
            
            </RelativeLayout>

            2.code of activity:


            package com.shaikhhamadali.blogspot.proximitysensor;
            
            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.content.Context;
            import android.widget.TextView;
            import android.widget.Toast;
            
            public class ProximitySensor extends Activity implements SensorEventListener{
             //SensorManager lets you access the device's sensors
             //declare Variables
             private SensorManager sensorManager;
             TextView tVProximity;
            
             /** Called when the activity is first created. */
             @Override
             public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_proximity_sensor);
            
              tVProximity = (TextView)findViewById(R.id.tVProximity);
              //create instance of sensor manager and get system service to interact with Sensor
              sensorManager= (SensorManager)getSystemService(Context.SENSOR_SERVICE);
              Sensor proximitySensor= sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
              if (proximitySensor == null){
               Toast.makeText(ProximitySensor.this,"No Proximity Sensor Found! ",Toast.LENGTH_LONG).show();
              }
             }
            
             @Override
             protected void onResume() {
              super.onResume();
              // register this class as a listener for the Proximity Sensor
              sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
                SensorManager.SENSOR_DELAY_NORMAL);
             }
             @Override
             protected void onPause() {
              // unregister listener
              super.onPause();
              sensorManager.unregisterListener(this);
             }
             @Override
             public void onAccuracyChanged(Sensor sensor, int accuracy) {
            
             }
             // called when sensor value have changed
             @Override
             public void onSensorChanged(SensorEvent event) {
              // The Proximity sensor returns a single value either 0 or 5(also 1 depends on Sensor manufacturer).
              // 0 for near and 5 for far 
              if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
               if(event.values[0]==0){
                tVProximity.setText("You are Near: "+String.valueOf(event.values[0]));
               }
               else{
                tVProximity.setText("You are Far: "+String.valueOf(event.values[0]));
               }
               
              }}
            }

            3. note that:



            4. conclusion:


            • Some information about how to use TYPE_PROXIMITY sensor.
            • know what are Sensors and how to use Sensors.
            • know that Proximity Sensor is used to check that device is near to any object or not.

            5. About the post:

            •  Almost every android mobile is shipped with sensors to measure various environmental conditions.Proximity sensors would be useful to reveal the nearness of an object to the phone. We might often experience that our phone screen would turn off when we bring the phone to our ears when we are in a call and the screen will turn on when we take it back. This is because the proximity sensor recognizes the object near the phone.
            • 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

            Friday, 25 October 2013

            In Room With No Light

            Android Sensor(Light Sensor)

            In Room With Dim Light

            Android Sensor(Light Sensor)

            In Room With Normal Light

            Android Sensor(Light Sensor)

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

            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: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=".LightSensor" >
             <TextView
                    android:id="@+id/TextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="50dp"
                    android:text="Light Sensor"
                    android:textColor="#0835C9"
                    android:textSize="30sp" />
                <TextView 
                android:id="@+id/tVMaxValue"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/TextView"
                android:textSize="20sp"/>
             <TextView 
                android:id="@+id/tVCurrentLight"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/tVMaxValue"
                android:layout_marginTop="10dp"
                android:textSize="20sp"
                />
            
            </RelativeLayout>

            2.code of activity:


            package com.shaikhhamadali.blogspot.lightsensor;
            
            import android.app.Activity;
            import android.content.Context;
            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 LightSensor extends Activity implements SensorEventListener{
             //SensorManager lets you access the device's sensors
             //declare Variables
             private SensorManager sensorManager;
                TextView tVMaxValue, tVCurrentLight;
              
                /** Called when the activity is first created. */
                @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_light_sensor);
                    tVMaxValue = (TextView)findViewById(R.id.tVMaxValue);
                    tVCurrentLight = (TextView)findViewById(R.id.tVCurrentLight);
              //create instance of sensor manager and get system service to interact with Sensor
                    sensorManager= (SensorManager)getSystemService(Context.SENSOR_SERVICE);
                    Sensor lightSensor= sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
                  
                    if (lightSensor == null){
                     Toast.makeText(LightSensor.this,"No Light Sensor Found! ",Toast.LENGTH_LONG).show();
                    }else{ float max =  lightSensor.getMaximumRange();
                      //Get Maximum Value From Light sensor
                       tVMaxValue.setText("Max Range: " + String.valueOf(max));
                       sensorManager.registerListener(this,lightSensor,SensorManager.SENSOR_DELAY_NORMAL);
                    }
                }
                 
                @Override
             protected void onResume() {
              super.onResume();
              // register this class as a listener for the lightSensor
              sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),
                SensorManager.SENSOR_DELAY_NORMAL);
             }
                @Override
             protected void onPause() {
              // unregister listener
              super.onPause();
              sensorManager.unregisterListener(this);
             }
             @Override
             public void onAccuracyChanged(Sensor sensor, int accuracy) {
              
             }
             // called when sensor value have changed
             @Override
             public void onSensorChanged(SensorEvent event) {
              // The light sensor returns a single value.
                 // Many sensors return 3 values, one for each axis.
                 if(event.sensor.getType()==Sensor.TYPE_LIGHT){
                   float currentLight = event.values[0];
                   if(currentLight<1){tVCurrentLight.setText("Current light: " + "no Light");}
                   else if(currentLight<5){tVCurrentLight.setText("Current light is Dim:" + String.valueOf(currentLight));}
                   else if(currentLight<10){tVCurrentLight.setText("Current light is Normal:" + String.valueOf(currentLight));}
                   else if(currentLight<100){tVCurrentLight.setText("Current light is Bright(Room):" + String.valueOf(currentLight));}
                   else tVCurrentLight.setText("Current light is Bright(Sun):" + String.valueOf(currentLight));
             }}
            }
            

            3. note that:


            4. conclusion:


            • Some information about how to use TYPE_LIGHT sensor.
            • know what are Sensors and how to use Sensors.
            • know that light readings change in different light.
            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

            Saturday, 19 October 2013

            Barometer using Type.Pressure Sensor

            Pressure Sensor

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



            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"
                tools:context=".Barometer" >
            
                <TextView
                    android:id="@+id/TextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="50dp"
                    android:text="@string/Heading"
                    android:textColor="#0835C9"
                    android:textSize="30sp" />
            
                <TextView
                    android:id="@+id/TVAirPressure"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:textColor="#08C9BD"
                    android:textSize="40sp" />
            
            </RelativeLayout>

            2.code of activity:
            package com.shaikhhamad.blogspot.barometer;
            
            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.app.Service;
            import android.view.Menu;
            import android.widget.TextView;
            
            public class Barometer extends Activity implements SensorEventListener{
             //SensorManager lets you access the device's sensors
             //declare Variables
             TextView textView,TVAirPressure;
             private SensorManager sensorManager;
            
             @Override
             protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_barometer);
              textView=(TextView)findViewById(R.id.TextView);
              TVAirPressure=(TextView)findViewById(R.id.TVAirPressure);
              //create instance of sensor manager and get system service to interact with Sensor
              sensorManager = (SensorManager) getSystemService(Service.SENSOR_SERVICE);
             }
             @Override
             protected void onResume() {
              super.onResume();
              // register this class as a listener for the Pressure Sensor
              sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE),
                SensorManager.SENSOR_DELAY_NORMAL);
             }
             // called when sensor value have changed
             @Override
             public void onSensorChanged(SensorEvent event) {
              if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
               float[] values = event.values;
               TVAirPressure.setText("" + values[0]);
              }
            
             }
             @Override
             public void onAccuracyChanged(Sensor sensor, int accuracy) {
            
             }
            
             @Override
             protected void onPause() {
              // unregister listener
              super.onPause();
              sensorManager.unregisterListener(this);
             }
            }

            3. note that:

            4. conclusion:

            • Some information about how to use TYPE_PRESSURE.
            • 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

            Friday, 18 October 2013

            List of Sensors Availble

            Create new Android Project


            Project Name: SensorsList

            //tested from 2.3.3 to current android sdk 
            Build Target: Android 2.3.3   //or greater than that
            Application Name: SensorsList
            Package Name: com.shaikhhamadali.blogspot.sensorslist
            Create layout file: activity_sensors_list

            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"
                tools:context=".SensorsList" >
            
                <TextView
                    android:id="@+id/textView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="List Of All The Sensors in Your Device"
                    android:textColor="#000000"
                    android:textSize="30sp"
                    android:textStyle="italic"
                    android:typeface="sans" />
            
                <ListView
                    android:id="@+id/listView1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/textView"
                    android:layout_centerInParent="true" >
                </ListView>
            
            </RelativeLayout>

            2.code of activity:
            package com.shaikhhamadali.blogspot.sensorslist;
            
            import java.util.ArrayList;
            import java.util.List;
            
            import android.hardware.Sensor;
            import android.hardware.SensorManager;
            import android.os.Bundle;
            import android.app.Activity;
            import android.content.Context;
            import android.widget.ArrayAdapter;
            import android.widget.ListView;
            
            public class SensorsList extends Activity {
             //variables
             private ListView listView;
             private SensorManager mSensorManager;
             //list of sensors
             private List<Sensor> deviceSensors = null;
             //list of sensors names
             private List<String> deviceSensorsList = new ArrayList<String>();
            
             @Override
             protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_sensors_list);
              //create instance of list view 
              listView = ((ListView) findViewById(R.id.listView1));
              //create instance of sensor manager and get system sensor service
              mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
              //get list of all types of sensors in you device
              deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
              /*you can get specific sensors by selecting type in getSensorList(type you want);*/
              for(Sensor s: deviceSensors){
               //get names of all the sensors in your device and add into list
               deviceSensorsList.add(s.getName());
              }
              listView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, deviceSensorsList));
             }
            }

            3. note that:

            4. conclusion:

            • Some information about how to get list of all/selected type sensors in device.
            • 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

            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

            Monday, 14 October 2013

            Sensors Overview:

            Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions. These sensors are capable of providing raw data with high precision and accuracy, and are useful if you want to monitor three-dimensional device movement or positioning, or you want to monitor changes in the ambient environment near a device. For example, a game might track readings from a device's gravity sensor to infer complex user gestures and motions, such as tilt, shake, rotation, or swing. Likewise, a weather application might use a device's temperature sensor and humidity sensor to calculate and report the dewpoint, or a travel application might use the geomagnetic field sensor and accelerometer to report a compass bearing.

            The Android platform supports three broad categories of sensors:

            • Motion sensors: These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
            • Environmental sensors: These sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.
            • Position sensors: These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.

            You can access sensors available on the device and acquire raw sensor data by using the Android sensor framework. The sensor framework provides several classes and interfaces that help you perform a wide variety of sensor-related tasks. For example, you can use the sensor framework to do the following:
            • Determine which sensors are available on a device.
            • Determine an individual sensor's capabilities, such as its maximum range, manufacturer, power requirements, and resolution.
            • Acquire raw sensor data and define the minimum rate at which you acquire sensor data.
            • Register and unregister sensor event listeners that monitor sensor changes.

            Introduction to Sensors:

            The Android sensor framework lets you access many types of sensors. Some of these sensors are hardware-based and some are software-based. Hardware-based sensors are physical components built into a handset or tablet device. They derive their data by directly measuring specific environmental properties, such as acceleration, geomagnetic field strength, or angular change. Software-based sensors are not physical devices, although they mimic hardware-based sensors. Software-based sensors derive their data from one or more of the hardware-based sensors and are sometimes called virtual sensors or synthetic sensors. The linear acceleration sensor and the gravity sensor are examples of software-based sensors.

            Some Hardware based Sensors are described below:
            • Sensor.TYPE_GYROSCOPE
            • Sensor.TYPE_MAGNETIC_FIELD
            • Sensor.TYPE_ACCELEROMETER
            Some Software based Sensors are described below:
            • Sensor.TYPE_ORIENTATION
            • Sensor.TYPE_GRAVITY: This comes in Hardware based Sensors too.
             

            Sensor Framework:

            You can access these sensors and acquire raw sensor data by using the Android sensor framework. The sensor framework is part of the android.hardware package and includes the following classes and interfaces:

            SensorManager: 
            You can use this class to create an instance of the sensor service. This class provides various methods for accessing and listing sensors, registering and unregistering sensor event listeners, and acquiring orientation information. This class also provides several sensor constants that are used to report sensor accuracy, set data acquisition rates, and calibrate sensors.
            Sensor: 
            You can use this class to create an instance of a specific sensor. This class provides various methods that let you determine a sensor's capabilities.
            SensorEvent:
            The system uses this class to create a sensor event object, which provides information about a sensor event. A sensor event object includes the following information: the raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp for the event.
            SensorEventListners:
            You can use this interface to create two callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.

            In a typical application you use these sensor-related APIs to perform two basic tasks:
            • Identifying sensors and sensor capabilities
              Identifying sensors and sensor capabilities at runtime is useful if your application has features that rely on specific sensor types or capabilities. For example, you may want to identify all of the sensors that are present on a device and disable any application features that rely on sensors that are not present. Likewise, you may want to identify all of the sensors of a given type so you can choose the sensor implementation that has the optimum performance for your application.
            • Monitor sensor events
              Monitoring sensor events is how you acquire raw sensor data. A sensor event occurs every time a sensor detects a change in the parameters it is measuring. A sensor event provides you with four pieces of information: the name of the sensor that triggered the event, the timestamp for the event, the accuracy of the event, and the raw sensor data that triggered the event.

            Sensor Availability:

            While sensor availability varies from device to device, it can also vary between Android versions. This is because the Android sensors have been introduced over the course of several platform releases. For example, many sensors were introduced in Android 1.5 (API Level 3), but some were not implemented and were not available for use until Android 2.3 (API Level 9). Likewise, several sensors were introduced in Android 2.3 (API Level 9) and Android 4.0 (API Level 14). Two sensors have been deprecated and replaced by newer, better sensors.

            So this was the basics and overview of Android Sensors.we will cover Both Hardware And Software Based Sensors,but our next tutorial would be on Sensor.TYPE_ACCELEROMETER.