Android Proximity Sensor

Android Proximity Sensor 
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);

}

}

}


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>
I Am Not The Owner Of These Code .I Merely Have Copied Them From Various Sources. The Only Thing I Did Is That I Am Going To Present Them In More Easy Way To Understand.

Comments

Popular posts from this blog

LED Blinking using 8051 Microcontroller and Keil C – AT89C51

Android Camera Example 2

Java Script to make text change text color