Sanjay Joshi Sanjay Joshi -4 years ago 242
Android Question

Using proximity sensor in android

I want to use proximity sensor in my project. I searched for proximity sensor tutorial. And I found a sensor tutorial at I tried to use proximity sensor as following code:

public void onSensorChanged(SensorEvent event)
if(event.sensor.getType() == Sensor.TYPE_PROXIMITY)
Toast.makeText(getApplicationContext(), "working", Toast.LENGTH_SHORT).show();

is implementing
. But its not working. Do I need to use any permission to use proximity sensor? Or My code is wrong for doing this stuff. Your help will be very appreciated. Thank you

Answer Source

I use this code:

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.Toast;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mProximity;

    protected void onCreate(Bundle savedInstanceState) {

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);


    protected void onResume() {
        mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);

    protected void onPause() {

    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
            if (event.values[0] >= -0.01 && event.values[0]<= 0.01) {
                Toast.makeText(getApplicationContext(), "near", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "far", Toast.LENGTH_SHORT).show();

    public void onAccuracyChanged(Sensor sensor, int accuracy) {


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download