Sunday, 11 August 2013

Proximity Sensor in Android example




                  

                      Proximity Sensor is used to determine how far the device is closer to an object. For example when user making/receiving a phone call, proximity sensor measures the distance between the device and the user's face.







I am going to implement this Proximity Sensor for playing/pause a music.

Steps to create the project::
  • create an android project.
  • create a layout xml with one textview (for updating playing/pause status).
  • place one music file in raw directory under res directory.
  • implement "SensorEventListener" interface and add unimplemented methods.
  • register the listener for Proximity Sensor.
  • play/pause the music based on the sensor.

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" >
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        android:textAppearance="?android:attr/textAppearanceMedium"
        tools:context=".MainActivity" />
</RelativeLayout>



MainActivity.java

import java.io.IOException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener{

    SensorManager sensorMgr;
    Sensor sensor;
    TextView textView;
    MediaPlayer player;
    boolean flag = false;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        textView = (TextView)findViewById(R.id.textView2);
        sensorMgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_PROXIMITY);
       
        player = MediaPlayer.create(getApplicationContext(), R.raw.music_file);
        try {
            player.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   
    @Override
    protected void onResume() {
           super.onResume();
           sensorMgr.registerListener(this, sensor,SensorManager.SENSOR_DELAY_NORMAL);
    }
   
    @Override
    protected void onPause() {
        super.onPause();
        sensorMgr.unregisterListener(this);
        player.stop();
    }
   
    public void onAccuracyChanged(Sensor sensor, int accuracy) {       
    }

    public void onSensorChanged(SensorEvent event) {
        if(event.sensor.getType() == sensor.TYPE_PROXIMITY){
            if(event.values[0] == sensor.getMaximumRange()){
                if(flag == true){
                    player.pause();
                    textView.setText("Pause");
                    flag = false;
                }else{
                    player.start();
                    textView.setText("Now Playing..!");
                    flag = true;
                }  
            }
        }
    }
}


AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sathish.example.proximitysensor"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="15" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

screenshots










click here to download the source code.