android 摇一摇事件触发

​
class SensorActivity: AppCompatActivity(), SensorEventListener{

    private var sensorManager:SensorManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager?
        val accelerometer = sensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        sensorManager?.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL)

    }

    override fun onSensorChanged(event: SensorEvent?) {
        event?:return
        if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]
            // 计算加速度的总值
            val acceleration = sqrt((x * x + y * y + z * z).toDouble())
            // 设置一个合适的阈值来检测摇晃
            if (acceleration > 12) {
               // 在这里执行摇一摇后的操作
            }
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        // 当传感器精度发生变化时的处理
    }

}

注意关闭传感器,避免不必要的耗电

sensorManager.unregisterListener(this);

你可能感兴趣的:(android,kotlin)