Sensor de proximidad en la aplicación de Android usando Jetpack Compose

El sensor de proximidad es uno de los sensores presentes en el dispositivo móvil que utilizan todos los que usan un teléfono inteligente. Este sensor está presente en los dispositivos móviles debajo de la sección del auricular. Este sensor se utiliza dentro del dispositivo móvil cuando el usuario está atendiendo una llamada para evitar la desconexión de la llamada, la pantalla se apaga automáticamente cuando el usuario sostiene el teléfono en la oreja. Cuando el teléfono se aleja de la oreja, la pantalla se enciende automáticamente. En este artículo, veremos cómo usar el sensor de proximidad en Android usando Jetpack Compose

Implementación paso a paso

Paso 1: crea un nuevo proyecto en Android Studio

Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Al elegir la plantilla, seleccione Actividad de composición vacía . Si no encuentra esta plantilla, intente actualizar Android Studio a la última versión. Demostramos la aplicación en Kotlin, así que asegúrese de seleccionar Kotlin como idioma principal al crear un nuevo proyecto.

Paso 2: Agregar un nuevo color en el archivo Color.kt

Vaya a aplicación > java > nombre del paquete de su aplicación > ui.theme > archivo Color.kt y agréguele el siguiente código. Se agregan comentarios en el código para conocer en detalle. 

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)

Paso 3: Agregar permiso para usar Sensor en AndroidManifest.xml

Vaya a la aplicación > manifiesto > AndroidManifest.xml y agregue el siguiente permiso en la etiqueta del manifiesto. 

XML

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

Paso 4: trabajar con el archivo MainActivity.kt

Vaya al archivo MainActivity.kt y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.kt . Se agregan comentarios dentro del código para comprender el código con más detalle.

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)
        )
    }
}

Ahora ejecute su aplicación para ver el resultado. 

Producción: 

Publicación traducida automáticamente

Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *