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 –>
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.
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.
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.