📜  Android 传感器示例

📅  最后修改于: 2022-05-13 01:55:10.328000             🧑  作者: Mango

Android 传感器示例

在我们的童年时代,我们都玩过许多 android 游戏,如 Moto Racing 和 Temple run,通过倾斜手机来改变字符的位置。因此,所有这些都是由于您的 Android 设备中存在的传感器而发生的。大多数 Android 设备都有内置传感器,用于测量运动、方向和各种环境条件。 Android Sensors 可用于监测设备的三维运动或设备环境的变化,例如光线、接近度、旋转、运动、磁场等。

传感器类型

  1. 运动传感器:这些传感器沿三个轴测量加速力和旋转力。此类别包括加速度计、重力传感器、陀螺仪和旋转矢量传感器。
  2. 位置传感器:这些传感器测量设备的物理位置。此类别包括方向传感器和磁力计。
  3. 环境传感器:这些传感器测量各种环境参数,例如环境空气温度和压力、光照和湿度。此类别包括气压计、光度计和温度计。

Android 传感器 API

我们可以使用 Android Sensor API 收集原始传感器数据。 Android 传感器 API 提供了许多类和接口。一些重要的类和接口是:

  1. SensorManager 类:传感器管理器用于访问设备中存在的各种传感器。
  2. 传感器类:传感器类用于获取有关传感器的信息,例如传感器名称、传感器类型、传感器分辨率、传感器类型等。
  3. SensorEvent 类:该类用于查找有关传感器的信息。
  4. SensorEventListener 接口:用于在传感器精度发生变化时执行一些操作。

示例:光传感器应用程序

这个应用程序将借助手机中的光传感器向我们显示房间内的光强度。

分步实施

第 1 步:在您的 android studio 中创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Kotlin作为编程语言。

第 2 步:使用 XML 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。

XML


 
      
    
 


Kotlin
package com.mrtechy.gfg_sensor
 
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatDelegate
 
class MainActivity : AppCompatActivity(), SensorEventListener {
 
      // Initialised sensorManager & two variables
      // for storing brightness value
    private lateinit var sensorManager: SensorManager
    private var brightness: Sensor? = null
    private lateinit var text: TextView
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // Set default nightmode
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
 
        // searched our textview id and stored it
        text = findViewById(R.id.tv_text)
 
        // setupSensor Called
        setUpSensor()
    }
 
    // Declared setupSensor function
    private fun setUpSensor() { 
      sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
      brightness = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
    }
 
    // These are two methods from sensorEventListner Interface
    override fun onSensorChanged(event: SensorEvent?) {
        if (event?.sensor?.type == Sensor.TYPE_LIGHT) {
            val light1 = event.values[0]
 
            text.text = "Sensor: $light1\n${brightness(light1)}"
        }
    }
    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        return
    }
     
    // Created a function to show messages according to the brightness
    private fun brightness(brightness: Float): String {
 
        return when (brightness.toInt()) {
            0 -> "Pitch black"
            in 1..10 -> "Dark"
            in 11..50 -> "Grey"
            in 51..5000 -> "Normal"
            in 5001..25000 -> "Incredibly bright"
            else -> "This light will blind you"
        }
    }
 
    // This is onResume function of our app
    override fun onResume() {
        super.onResume()
        sensorManager.registerListener(this, brightness, SensorManager.SENSOR_DELAY_NORMAL)
    }
 
    // This is onPause function of our app
    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(this)
    }
}



第 3 步:使用 MainActivity.kt

转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。

科特林

package com.mrtechy.gfg_sensor
 
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatDelegate
 
class MainActivity : AppCompatActivity(), SensorEventListener {
 
      // Initialised sensorManager & two variables
      // for storing brightness value
    private lateinit var sensorManager: SensorManager
    private var brightness: Sensor? = null
    private lateinit var text: TextView
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // Set default nightmode
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
 
        // searched our textview id and stored it
        text = findViewById(R.id.tv_text)
 
        // setupSensor Called
        setUpSensor()
    }
 
    // Declared setupSensor function
    private fun setUpSensor() { 
      sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
      brightness = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
    }
 
    // These are two methods from sensorEventListner Interface
    override fun onSensorChanged(event: SensorEvent?) {
        if (event?.sensor?.type == Sensor.TYPE_LIGHT) {
            val light1 = event.values[0]
 
            text.text = "Sensor: $light1\n${brightness(light1)}"
        }
    }
    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        return
    }
     
    // Created a function to show messages according to the brightness
    private fun brightness(brightness: Float): String {
 
        return when (brightness.toInt()) {
            0 -> "Pitch black"
            in 1..10 -> "Dark"
            in 11..50 -> "Grey"
            in 51..5000 -> "Normal"
            in 5001..25000 -> "Incredibly bright"
            else -> "This light will blind you"
        }
    }
 
    // This is onResume function of our app
    override fun onResume() {
        super.onResume()
        sensorManager.registerListener(this, brightness, SensorManager.SENSOR_DELAY_NORMAL)
    }
 
    // This is onPause function of our app
    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(this)
    }
}


输出: