Today Sensor are becoming very prominent in Android
Smart phones. Without them an any app look dull and ineffective. Today sensors
plays a vital role in android smartphones. Today sensor are used in Application
like Gaming, Educational etc. So managing the Sensor has become the most important.
So here we are, Android itself supports several types of sensors via the library
SensorManager, for
example the accelerometer, gyroscope etc. Since Testing your an Android App as
developer with an emulator is worthless since it does not support any
particular sensor hardware. So we need an real device to test it. Now let’s go
little bit technically in the topic how to create and manage your first app with
sensors.
So we can access a SensorManager via getSystemService(SENSOR_SERVICE) which an by
default code which we will be needing to write. The Sensor class defines several
constants for accessing the different types of sensors like:
|
|
TYPE_ACCELEROMETER
|
describing
an accelerometer sensor type.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
TYPE_AMBIENT_TEMPERATURE
|
describing
an ambient temperature sensor type
|
|
|
|
|
|
|
|
|
|
|
TYPE_GRAVITY
|
describing
a gravity sensor type.
|
|
|
|
|
|
|
|
|
|
|
TYPE_GYROSCOPE
|
describing
a gyroscope sensor type
|
|
|
|
|
|
|
|
|
|
|
TYPE_LIGHT
|
describing
a light sensor type.
|
|
|
|
|
|
|
|
|
|
|
TYPE_LINEAR_ACCELERATION
|
describing
a linear acceleration sensor type.
|
|
|
|
|
|
|
|
|
|
|
TYPE_MAGNETIC_FIELD
|
describing
a magnetic field sensor type.
|
|
|
|
|
|
|
|
|
|
|
|
describing
a orientation sensor type.
|
|
|
|
|
|
|
|
|
|
|
TYPE_PRESSURE
|
describing
a pressure sensor type
|
|
|
|
|
|
|
|
|
|
|
TYPE_PROXIMITY
|
describing
a proximity sensor type.
|
|
|
|
|
|
|
|
|
|
|
TYPE_RELATIVE_HUMIDITY
|
describing
a relative humidity sensor type.
|
|
|
|
|
|
|
|
|
|
|
TYPE_ROTATION_VECTOR
|
describing
a rotation vector sensor type.
|
|
|
|
|
|
|
|
|
|
|
TYPE_TEMPERATURE
|
describing
a temperature sensor type.
|
|
|
|
|
|
|
|
|
|
We will be discussing about each
type of sensor in detail. Just for time being you just memorize them.
We can access different types of
Sensor via the sensorManager.getDefaultSensor () method, which takes the
type of sensor requested and then returns the default sensor matching it. If we need to access the raw sensors we have to use getSensorList
.
One more thing for starting any service like
we are invoking an Sensor Activity then we have to register that activity with
that particular device which can be done with SensorEventListener by registering an object on it. This listener will get informed,
if the sensor data changes.
Since during invoke of an Sensor
Activity lot of battery is required which will be using if an activity is idle
which can cause to degrade your battery life. So to avoid
An unnecessary
usage of battery we have to register our listener in the onResume() method and de-register it in theonPause() method. These are the part of activity-life
cycle which we don’t have bother about. I will be discussing it in my further
articles.
Here basically I will be going to discuss mainly
about Accelerometer.So now let see how to make it. Here are some snaps for each
steps which will be helpful for you to make your application.
I think you are familiar about
how to install configure an android environment in your pc.If not I will be posting it soon then. So just start an
eclipse go to file à new à android project.Give the required project name,
package name etc. Than go to src folder open your main .java file to edit the
code.
Also open the main.xml file from res à layout àmain.xml
Make the following Change in your
layout main.xml as given below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Shake
to change color and to get toast" />
</LinearLayout>
This layout file is to
display the first screen to be visible when user logins.
Change the code in your Activity to the following.
package sensor.accelero;
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.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
These are the libraries which will be used while developing our simple
app.I will explain each of it one by one.
Android.app.activity à
The Activity class is an important part of an
application's overall lifecycle, and the way activities are launched and put
together is a fundamental part of the platform's application model.
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new
activity is started, it is placed on the top of the stack and becomes the
running activity -- the previous activity always remains below it in the stack,
and will not come to the foreground again until the new activity exits.
The following diagram shows the important
state paths of an Activity. The square rectangles represent callback methods we
can implement to perform operations when the Activity moves between states. The
colored ovals are major states the Activity can be in.
android.graphics.Color à
The Color class defines methods for creating
and converting color ints. Colors are represented as packed ints, made up of 4
bytes: alpha, red, green, blue. The values are unpremultiplied, meaning any
transparency is stored solely in the alpha component, and not in the color
components.
android.hardware.Sensor à Class
representing a sensor which I have described above.
android.hardware.SensorEventListener à
This class
represents a Sensor event and holds informations such as the sensor's
type, the time-stamp, accuracy and of course the sensor's data.
Definition
of the coordinate system used by the SensorEvent API.
The coordinate-system is defined relative to the
screen of the phone in its default orientation.
axes are
not swapped when the device's screen orientation changes.
The X axis
is horizontal and points to the right, the Y axis is vertical and points up and
the Z axis points towards the outside of the front face of the screen. In this
system, coordinates behind the screen have negative Z values.
This
coordinate system is different from the one used in the Android 2D APIs where
the origin is in the top-left corner.
android.hardware.SensorManager à
SensorManager lets us access the device's sensors
.
To get an instance of this class by
calling Context.getSystemService()
with
the argument SENSOR_SERVICE
.
Also we have to care that we should switch off the
sensors when they are not used, failing so it will drain our battry and also
reduce the battery life.
I think you are familiar with these
libraries
android.os.Bundle
à A mapping from String values to various Parcelable
types.
android.view.View à Visual indicator of progress in some operation. For ex
TextView, SurfaceView
android.widget.Toast à When
the view is shown to the user, appears as a floating view over the application.
The idea is to be as unobtrusive as possible, while still showing the user the
information you want them to see.
android.view.Window à
This is an abstract base class for a top-level window
look and behaviors. An instance of this class must be used as the top-level
view added to the window manager. It provides standard UI facilities such as a
background, title area, default key processing, etc.
android.view.WindowManager. à
The interface that apps use to talk to the
window manager.To use this we have to use Context.getSystemService(Context.WINDOW_SERVICE)
to
get one of these.
Now
in class Main write the following code
public class Main extends
Activity implements SensorEventListener {
//Here extends and implements means inheritance. Here class Main is
Inheriting the features of class activity and SensorEventListener.
private SensorManager
sensorManager;
// This is creating an instance of SensorManager.
// Note: It is Case sensitive.
So be careful with that.
private boolean color = false;
/*** Creating a Boolean variable. Boolean is a variable which accepts two
variable true or false. Initially I am giving it as false. Means no color is
set initially. ***/
private View view;
// This is creating an view.
private long
lastUpdate;
/*** This is the update variable which checks for the update.If update is
less than 200ms than it will automatically change the background color.***/
/** Called when the activity is first created. I think */
@Override
public void
onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
/*** This line will remove the The Action Bar from the activity screen
which we generally see with the title of the app.***/
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
/*** getWindow() will reterive the initial window screen.It do so by
taking flag values. The flag values set will set the initial flag to layout of
the screen to the full screen. It is the notification that screen is set to
FULL_SCREEN mode***/
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = findViewById(R.id.textView);
/*** This is getting an default UI id of an textview defined in the
main.xml***/
view.setBackgroundColor(Color.BLUE);
/***Setting up the Background to Blue initially when activity is
started.***/
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
/*** This is getting a System Service through getSystemService()
As I discussed above.***/
lastUpdate = System.currentTimeMillis();
/*** lastUpdate variable is set to current system time using
System.currentTimeMillis(); ***/
}
@Override
public void
onSensorChanged(SensorEvent event)
// TODO AUTO-GENERATED CLASS
/*** They is the Auto generated class. When you implement the
sensoreventlistener class it will auto generate some by default functions***/
{
if(event.sensor.getType()
== Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
/** This is checking if the sensor which the app get is TYPE_ACCELEROMETER
or not. ***/
}
}
private void
getAccelerometer(SensorEvent event) {
float[] values =
event.values;
/* Movement of the phone in x
,y, z direction is stored in values of given event in form of arrays.***/
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();
// Storing the actual time.
if (accelationSquareRoot
>= 1)
/***checking if that value is greater than 1 or not ***//
{
if (actualTime -
lastUpdate < 100) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this,
"Device was shaked", Toast.LENGTH_LONG)
.show();
// Toast is made when device is shaken
/*** And color is changed. Accordingly. We can also Define other Activity
in it.***/
if (color) {
view.setBackgroundColor(Color.CYAN);
} else {
view.setBackgroundColor(Color.RED);
}
color = !color;
}
}
@Override
public void
onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
protected void
onResume() {
super.onResume();
// registering this class as a
listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
// Giving some delay to register.
}
@Override
protected void
onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
/*** this à it is showing in which reference
you are going to unregister your sensor.***/
}
}
/*** It’s the
unregistering of the service so as to save battery life.
Final Output
screen
When you Run this application.