How to use sensors in android app

Hi, everyone today we are going to learn how to use sensors in android app.A sensor in smartphones is any of a number of different  types of sensitive device installed in your phone to gather data for various purposes.

Sensors are used on  Android Phones for detecting the state of the nearby environment plus motion and placement of the phone.

The sensor types are:.

  •  Accelerometer, The Accelerometer gives the acceleration of the device along the 3 axes.
  • Gyroscope. Gives the rate of rotation about the axes.
  • Magnetometer. Gives the ambient magnetic field along the 3 axes.
  • Ambient Temperature. Returns the room temperature.
  • Heart Rate Sensor. This gives the heart beat rate of the person currently touching the phone.
  • Light Sensor. Gives the ambient light in SI lux units.
  • Proximity Sensor. Gives the distance of the phone from the closest visible surface. This is the wake up sensor.
  • Pressure Sensor or Barometer. Gives the atmospheric pressure in  hectopascal (hPa).
  • Relative Humidity.Gives the ambient air humidity in percent.

    In this post we are going to learn how to use Accelerometer and Light_Sensor in our android app.Accelerometer in phones are used to detect the movements of phone and its speed etc.Light sensor is used to start flash light,And to adjust Screen brightness etc.To use these sensors we will take five buttons in our layout to detect the accelerometer and three textviews to show its fluctuation.
    As you can see bellow:-

    To use flash light by using  Light_Sensor we must have to take permissions from android manifets.We have to take two permissions i.e uses permissions and uses feature permission For Using Camera.As you can see bellow:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ashuandroid.sensorslist">
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-feature android:name="android.hardware.Camera"></uses-feature>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Code for using these  two sensors in the program are given bellow:-
In this program we use to change colors of buttons which we set on the four corner and at the middle of our layout it  shows where the mobile will tilt by using Accelerometer Sensor.
To use Sensors we have to implements SensorEventListener in inner class in main activity and have to implements its methods.
Code are as follows:-

package com.ashuandroid.sensorslist;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    SensorManager sManager;      //object of sensor manager.
    Sensor sensor,sensor2;       //Object of sensors.
    TextView tv1,tv2,tv3,tv4;
    Camera camera;
    Parameters param;
    Button topleft,topright,bottomleft,bottomright,middle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_main);
            tv1 = (TextView) findViewById(R.id.tv1);
            tv2 = (TextView) findViewById(R.id.tv2);
            tv3 = (TextView) findViewById(R.id.tv3);
            tv4=(TextView)findViewById(R.id.tv4);
            topleft = (Button) findViewById(R.id.topleft);
            topright = (Button) findViewById(R.id.topright);
            bottomleft = (Button) findViewById(R.id.bottomleft);
            bottomright = (Button) findViewById(R.id.bottomright);
            middle = (Button) findViewById(R.id.middle);
            sManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

            sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            sensorlistener sensorlis = new sensorlistener();
            sManager.registerListener(sensorlis, sensor, SensorManager.SENSOR_DELAY_NORMAL);


            camera=Camera.open();
            param = camera.getParameters();

            sensor2 = sManager.getDefaultSensor(Sensor.TYPE_LIGHT);
            lightlistener lis = new lightlistener();
            sManager.registerListener(lis, sensor2, SensorManager.SENSOR_DELAY_NORMAL);
        }
        catch (Exception ex)
        {
            setTitle(""+ex.getMessage());
        }
    }
    public class sensorlistener implements SensorEventListener
    {
        @Override
        public void onSensorChanged(SensorEvent event) {
            try {
                float x, y, z;
                x = event.values[0];
                y = event.values[1];
                z = event.values[2];
                tv1.setText("" + x);
                tv2.setText("" + y);
                tv3.setText("" + z);
                if (y > 0) {

                    if (x > 0) {
                        bottomleft.setBackgroundColor(Color.MAGENTA);
                        topleft.setBackgroundColor(Color.BLUE);
                        topright.setBackgroundColor(Color.BLUE);
                        bottomright.setBackgroundColor(Color.BLUE);
                        middle.setBackgroundColor(Color.BLUE);

                    }

                    if (x < 0) {
                        bottomright.setBackgroundColor(Color.MAGENTA);
                        topright.setBackgroundColor(Color.BLUE);
                        topleft.setBackgroundColor(Color.BLUE);
                        bottomleft.setBackgroundColor(Color.BLUE);
                        middle.setBackgroundColor(Color.BLUE);
                    }
                } else if (y < 0) {

                    if (x < 0) {
                        topright.setBackgroundColor(Color.MAGENTA);
                        topleft.setBackgroundColor(Color.BLUE);
                        bottomright.setBackgroundColor(Color.BLUE);
                        bottomleft.setBackgroundColor(Color.BLUE);
                        middle.setBackgroundColor(Color.BLUE);
                    }

                    if (x > 0) {
                        topleft.setBackgroundColor(Color.MAGENTA);
                        bottomleft.setBackgroundColor(Color.BLUE);
                        bottomright.setBackgroundColor(Color.BLUE);

                        topright.setBackgroundColor(Color.BLUE);
                        middle.setBackgroundColor(Color.BLUE);
                    }
                } else {
                    middle.setBackgroundColor(Color.MAGENTA);
                    topleft.setBackgroundColor(Color.BLUE);
                    topright.setBackgroundColor(Color.BLUE);
                    bottomright.setBackgroundColor(Color.BLUE);
                    bottomleft.setBackgroundColor(Color.BLUE);
                }
            }
            catch (Exception ex)
            {
                setTitle(ex.getMessage());
            }
        }
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }
    public class lightlistener implements SensorEventListener   //For using Light_Sensor
    {

        @Override
        public void onSensorChanged(SensorEvent event) {
            try {
                float a = event.values[0];
                tv4.setText("Light : " + a);
                if (a < 1) {
                    param.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    camera.setParameters(param);
                    camera.startPreview();
                } else {
                    param.setFlashMode(Parameters.FLASH_MODE_OFF);
                    camera.setParameters(param);
                    camera.stopPreview();
                }
            }
            catch (Exception ex)
            {
                tv4.setText(ex.getMessage());
            }
   }
     @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }
}

 

Leave a Reply