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: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads