Skip to content
Related Articles

Related Articles

How to Use Proximity Sensor in Android?
  • Last Updated : 23 Feb, 2021

Proximity Sensor is one of the sensors present in mobile devices which we use almost every day. This sensor is present in the top section of your phone. The sensor is used to detect the presence of any object in the proximity of the phone. This sensor is used in many calling apps when the user keeps his phone on his ears for listening then the screen automatically turns off so to avoid unnecessary screen touch events while on call. To handle this case calling apps to use proximity sensors. In this article, we will see How to use the Proximity Sensor in our Android App. 

Implementation of Proximity Sensor

A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add permissions to use proximity sensor in our Android App



Add the following line in the AndroidManifest.xml file.

<!– Permission for using proximity sensor –>

<uses-permission android:name=”android.hardware.sensor.proximity”/>

Step 3: Working with the activity_main.xml

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.  

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <!--Text view to display sensor status-->
    <TextView
        android:id="@+id/sensorStatusTV"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textAlignment="center"
        android:textSize="50dp" />
  
</RelativeLayout>

Step 4: Working with the MainActivity.java file

Navigate to the app > java > your apps package name > MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. 

Java




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.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    // Creating variables for text view, 
    // sensor manager and our sensor.
    TextView sensorStatusTV;
    SensorManager sensorManager;
    Sensor proximitySensor;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sensorStatusTV = findViewById(R.id.sensorStatusTV);
          
        // calling sensor service.
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
          
        // from sensor service we are 
        // calling proximity sensor
        proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
          
        // handling the case if the proximity 
        // sensor is not present in users device.
        if (proximitySensor == null) {
            Toast.makeText(this, "No proximity sensor found in device.", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            // registering our sensor with sensor manager.
            sensorManager.registerListener(proximitySensorEventListener,
                    proximitySensor,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
  
    // calling the sensor event class to detect
    // the change in data when sensor starts working.
    SensorEventListener proximitySensorEventListener = new SensorEventListener() {
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // method to check accuracy changed in sensor.
        }
  
        @Override
        public void onSensorChanged(SensorEvent event) {
            // check if the sensor type is proximity sensor.
            if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
                if (event.values[0] == 0) {
                    // here we are setting our status to our textview..
                    // if sensor event return 0 then object is closed
                    // to sensor else object is away from sensor.
                    sensorStatusTV.setText("Near");
                } else {
                    sensorStatusTV.setText("Away");
                }
            }
        }
    };
}

Output: 

Now run the app on your real device to test the sensor. While testing the app move any object or your hand towards the top section of your phone. 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :