Open In App

Proximity Sensor in Android App using Jetpack Compose

Last Updated : 13 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Proximity Sensor is one of the sensors present in the mobile device which is used by everyone using smartphone. This sensor is present in mobile devices under the earpiece section. This sensor is used within the mobile device when the user is attending a call to prevent the disconnection of the call the screen switches off automatically when the user holds the phone on-ear. When the phone goes away from the ear the screen is automatically turned on. In this article, we will look at how to use the Proximity sensor in Android using Jetpack Compose

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 3: Adding permission for using Sensor in AndroidManifest.xml

Navigate to the app > manifest > AndroidManifest.xml and add the below permission in the manifest tag. 

XML




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


Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.newcanaryproject
 
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
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import coil.compose.rememberAsyncImagePainter
import com.example.newcanaryproject.ui.theme.*
import java.util.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying
                // background color for our application
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
                        // in scaffold we are specifying top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying tile as a text
                                    Text(
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "Proximity Sensor Example",
                                         
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
                                         
                                        // on below line we are
                                        // specifying text alignment.
                                        textAlign = TextAlign.Center,
                                         
                                        // on below line we are
                                        // specifying color for our text.
                                        color = Color.White
                                    )
                                }
                            )
                        }
                    ) {
                        // on below line we are calling proximity
                        // sensor method to use proximity sensor.
                        ProximitySensor()
                    }
                }
            }
        }
    }
}
 
// on below line we are creating a proximity
// sensor function to use proximity sensor.
@Composable
fun ProximitySensor() {
    // on below line we are creating
    // a variable for a context
    val ctx = LocalContext.current
     
    // on below line we are creating a variable for sensor manager and initializing it.
    val sensorManager: SensorManager = ctx.getSystemService(Context.SENSOR_SERVICE) as SensorManager
     
    // on below line we are creating a variable for proximity sensor and initializing it.
    val proximitySensor: Sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY)
     
    // on below line we are creating a string variable for
    // sensor status to set our sensor status.
    val sensorStatus = remember {
        mutableStateOf("")
    }
    // on below line we are creating a variable
    // for sensor event listener and initializing it.
    val proximitySensorEventListener = object : SensorEventListener {
        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
            // method to check accuracy changed in sensor.
        }
 
        // on below line we are creating a sensor on sensor changed
        override fun onSensorChanged(event: SensorEvent) {
            // check if the sensor type is proximity sensor.
            if (event.sensor.type == Sensor.TYPE_PROXIMITY) {
                // on below line we are checking if the
                // object is near or away from the sensor.
                if (event.values[0] == 0f) {
                    // if sensor event return 0 then
                    // object is near to the sensor
                    sensorStatus.value = "Near"
                } else {
                    // to sensor else object is away from sensor.
                    sensorStatus.value = "Away"
                }
            }
        }
    }
 
    // on below line we are registering listener for our sensor manager.
    sensorManager.registerListener(
        // on below line we are passing
        // proximity sensor event listener
        proximitySensorEventListener,
         
        // on below line we are
        // setting proximity sensor.
        proximitySensor,
         
        // on below line we are specifying
        // sensor manager as delay normal
        SensorManager.SENSOR_DELAY_NORMAL
    )
    // on below line we are creating a column
    Column(
        // on below line we are specifying modifier
        // and setting max height and max width for our column
        modifier = Modifier
            .fillMaxSize()
            .fillMaxHeight()
            .fillMaxWidth()
            // on below line we are
             // adding padding for our column
            .padding(5.dp),
        // on below line we are specifying horizontal
        // and vertical alignment for our column
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        // on below line we are creating a simple text
        // in which we are displaying a text as Object is
        Text(
            text = "Object is",
            // on below line we are setting text color
            color = Color.Black,
             
            // on below line we are specifying font weight
            fontWeight = FontWeight.Bold,
             
            // on below line we are specifying font family.
            fontFamily = FontFamily.Default,
             
            // on below line we are specifying
            // font size and padding from all sides.
            fontSize = 40.sp, modifier = Modifier.padding(5.dp)
        )
        // on below line we are creating a text for displaying
        // sensor status weather object is near or away
        Text(
            text = sensorStatus.value,
            // on below line we are setting color for our text
            color = Color.Black,
             
            // on below line we are setting font weight as bold
            fontWeight = FontWeight.Bold,
             
            // on below line we are setting font family
            fontFamily = FontFamily.Default,
             
            // on below line we are setting font family and padding
            fontSize = 40.sp, modifier = Modifier.padding(5.dp)
        )
        // on below line we are creating a text for displaying a sensor.
        Text(
            text = "Sensor",
            // on below line we are displaying a text color
            color = Color.Black,
             
            // on below line we are setting font weight
            fontWeight = FontWeight.Bold,
             
            // on below line we are setting font family
            fontFamily = FontFamily.Default,
             
            // on below line we are setting font size and padding.
            fontSize = 40.sp, modifier = Modifier.padding(5.dp)
        )
    }
}


Now run your application to see the output of it. 

Output: 



Similar Reads

Android - Proximity Sensor using Kotlin
Proximity Sensor is one of the sensors in mobile devices we use almost daily. 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 t
4 min read
How to Use Proximity Sensor in Android?
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 scre
3 min read
Android Jetpack Compose - Interoperability Using Compose in XML Layouts
Writing UI in jetpack compose can be fun, but can be difficult to migrate your whole project into Compose at one time. Fortunately, Jetpack Compose provides Interoperability api to use compose in existing XML views so that you can migrate to compose slowly. Prerequisites: Knowledge of Jetpack Compose.Knowledge of KotlinKnowledge of Android’s View.
3 min read
Torch App in Android using Jetpack Compose
Nowadays almost all mobile devices come with a flashlight that is used by the camera. Along with that, this same flashlight is also used as a torch on android devices. For using this flashlight there are many android applications named Torch to use this flashlight as a torch. In this article, we will be creating a simple torch application in androi
6 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Android Jetpack Compose - Build a BMI Calculator App from Scratch
Body Mass Index (BMI) is a widely used measure of body fat based on height and weight. With the rise of health consciousness, BMI calculators have become popular tools to monitor and manage one's weight and health. In this article, we will explore how to develop a BMI Calculator app for Android using Jetpack Compose and Material 3. Jetpack Compose
8 min read
Android Jetpack Compose - Create a Movie App
In the modern digital era, the demand for movie apps is soaring. These applications provide users with an immersive experience, allowing them to discover, explore, and enjoy a wide range of movies. Jetpack Compose, a declarative UI toolkit for Android, has gained immense popularity due to its simplicity, flexibility, and powerful features. In this
7 min read
Start a New Activity using Intent in Android using Jetpack Compose
In Android OS, an Intent is a mechanism used to navigate a user to another activity or application to achieve a specific task. In general, Intents are used to progress to the next activity or come back to the previous activity. [caption width="800"] [/caption] In this article, we will show you how you could start a New Activity using Intent in Andr
4 min read
How to Update Data in API using Retrofit in Android using Jetpack Compose?
Android applications use APIs within Android Applications to access data from databases. We can perform several operations using APIs such as Reading, Writing, and Updating our Data in the Database. In this article, we will take a look at How to Update Data in API using Retrofit in Android using Jetpack Compose. Note: If you are seeking Java code f
9 min read
How to Post Data to API using Volley in Android using Jetpack Compose?
APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android using Volley in Jetpack Compose. Note: If you are
9 min read
Article Tags :