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.

7 comments:

  1. music does not get start but the sensor works properly

    ReplyDelete
    Replies
    1. This code will work, else you can play a audio file from external memory.

      Delete
  2. how to sensor works properly when mobile screen is locked ? Is it possible to run in background if yes can you suggest me please?

    ReplyDelete
    Replies
    1. Yes its possible, you have to create Android Service and call the "register sensor" inside the onStartCommand method of Service.

      Delete
  3. Proximity App: PROXIMITY is a relational knowledge discovery system designed and implemented by the Knowledge Discovery Lab at the Department of Computer Science at the University of Massachusetts Amherst.

    ReplyDelete
  4. No entiendo el codigo no funciona salen muchos errores

    ReplyDelete
    Replies
    1. Hi, just get the latest source code from this GitHub link .
      You can download the sample apk file also.

      Delete