Android Accelerometer Example


In this sample application we will put the android accelerometer sensor into use . Nowadays accelerometer is used more in motion games where the user tilts the phone for a specific action to take place or used for shake detection. It has become common to shake the device to reset the application or erase a canvas in paint apps.

In this example we will change the image in the ImageView with respect to the users actions (like tilting the phone up,down right and left).Like we used for the proximity sensor example we use the SensorManager class and get the accelerometer sensor service. On the overridden method onSensorChanged we monitor the sensor values of all 3 axises (x ,y & z). Keep a threshold valued of 2.0 for center and change the image according the the axis values. Hope you got the idea.


Now lets start:

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the activity as AccelerometerActivity(AccelerometerActivity.java) and layout as activity_accelerometer.xml.

2.Now let us design the UI for the AccelerometerActivity i.e activity_accelerometer.xml with an ImageView and a TextView.Have images in drawable folder to differentiate each tilting motion(Here I have images for center,top,right,bottom and left).

activity_accelerometer.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relative"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Tilt the phone to see the difference" />

<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/txt"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"
android:src="@drawable/center" />
</RelativeLayout>

3.Now in the AccelerometerActivity use a logic to identify the tilting action and replace the images accordingly. Do not forget to unregister the sensor to save battery.

AccelerometerActivity.java 

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.ImageView;
import android.widget.TextView;

public class AccelerometerActivity extends Activity implements
  SensorEventListener {

 private SensorManager mSensorManager;
 private Sensor mAccelerometer;
 TextView title;
 ImageView iv;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_accelerometer);
  mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  mAccelerometer = mSensorManager
    .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  title = (TextView) findViewById(R.id.txt);
  iv = (ImageView) findViewById(R.id.imageView1);
 }

 @Override
 public void onAccuracyChanged(Sensor arg0, int arg1) {
  // TODO Auto-generated method stub
 }

 @Override
 public void onSensorChanged(SensorEvent event) {
  float x = event.values[0];
  float y = event.values[1];
  float z = event.values[2];
  if (Math.abs(x) > Math.abs(y)) {
   if (x < 0) {
    iv.setImageResource(R.drawable.right);
   }
   if (x > 0) {
    iv.setImageResource(R.drawable.left);
   }
  } else {
   if (y < 0) {
    iv.setImageResource(R.drawable.top);
   }
   if (y > 0) {
    iv.setImageResource(R.drawable.bottom);
   }
  }
  if (x > (-2) && x < (2) && y > (-2) && y < (2)) {
   iv.setImageResource(R.drawable.center);
  }
 }

 @Override
 protected void onResume() {
  super.onResume();
  mSensorManager.registerListener(this, mAccelerometer,
    SensorManager.SENSOR_DELAY_NORMAL);
 }

 @Override
 protected void onPause() {
  super.onPause();
  mSensorManager.unregisterListener(this);
 }
}



4.Run the project by rightclicking project Run as → android project in an android device.

Output:

The output of this example would be similar to the one as follows:

 


Android Proximity Sensor Example


Every android mobile is shipped with sensors to measure various environmental conditions. In this example we will see how to use the proximity sensors in an android application. 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.

In this example we will change the image in the ImageView w.r.t the nearness of any object to the phone. Check the sensor functionality by covering the sensor region (mostly the top left of the phone) with your hand .
So lets start

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the activity as SensorActivity(SensorActivity.java) and layout as sensor_screen.xml.

2.Now let us design the UI for the SensorActivity i.e sensor_screen.xml with an ImageView.Have two images in drawable folder to differentiate near and far activity.

sensor_screen.xml:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".SensorActivity" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/far" />

</RelativeLayout>

3.Now in the SensorActivity we access the device sensor using SensorManager, an instance of this class is got by calling getSystemService(SENSOR_SERVICE) . We implement the class with the SensorEventListener interface to override its methods to do actions on sensor value change.

SensorActivity.java:

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;

public class SensorActivity extends Activity implements SensorEventListener {
 private SensorManager mSensorManager;
 private Sensor mSensor;
 ImageView iv;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.sensor_screen);
  mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
  iv = (ImageView) findViewById(R.id.imageView1);
 }

 protected void onResume() {
  super.onResume();
  mSensorManager.registerListener(this, mSensor,
    SensorManager.SENSOR_DELAY_NORMAL);
 }

 protected void onPause() {
  super.onPause();
  mSensorManager.unregisterListener(this);
 }

 public void onAccuracyChanged(Sensor sensor, int accuracy) {
 }

 public void onSensorChanged(SensorEvent event) {
  if (event.values[0] == 0) {
   iv.setImageResource(R.drawable.near);
  } else {
   iv.setImageResource(R.drawable.far);
  }
 }
}

4.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:

 


View Microsoft Word Document In Android - Example


In this Example we will see how to view a ms word document through an android app. Here we will open the .doc file saved in the SD card with an application which can view the doc file such as Quick Office , Office suite or any other application capable of reading .doc or docx files.

On tapping a button we check for the existence of the .doc file in the SD card. If the file exists we call the reader application via Intents. In the due course if the reader application is not found it is notified by catching the exception ActivityNotFoundException.


So lets start:

1.Create an Android Application Project with any Project Name and Package Name. Create an Activity and Layout file for the same like MainActivity & activity_main.

2.Design the screen for the activity with a button as below

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
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=".Vibrator">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="124dp"
android:text="Welcome to AndroidBite !!!"
android:textColor="@android:color/black"
android:textSize="20sp"/>

<Button
android:id="@+id/bPressMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Press Me !!!"/>

</RelativeLayout>
3.Now in the activity, we create a File instance and construct it using specified directory and name. Then we set the Uri from the file instance and start the intent Intent.ACTION_VIEW . This intents data is set with the uri and the MIME Type for .doc file is set as application/msword before calling the intent.

For docx files use "application/vnd.openxmlformats-officedocument.wordprocessingml.document" as MIME type

MainActivity.java:
import java.io.File;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Button button = (Button) findViewById(R.id.bPressMe);

  button.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {

    File file = new File(Environment.getExternalStorageDirectory(),
      "Help Desk Voice Flow.doc");

    try {
     if (file.exists()) {
      Uri path = Uri.fromFile(file);
      Intent objIntent = new Intent(Intent.ACTION_VIEW);
      // replace "application/msword" with
      // "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      // for docx files
      // objIntent.setDataAndType(path,"application/msword");
      objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(objIntent);
     } else {
      Toast.makeText(MainActivity.this, "File NotFound",
        Toast.LENGTH_SHORT).show();
     }
    } catch (ActivityNotFoundException e) {
     Toast.makeText(MainActivity.this,
       "No Viewer Application Found", Toast.LENGTH_SHORT)
       .show();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });

 }

}
4.Include the WRITE_EXTERNAL_STORAGE permission in the manifest file(permission for both reading and writing).
5.Run the application by right clicking the project Run As->Android Application. If everything goes well the output will be similar to the one below

Output: