/* * This file is part of the BmapLite. * Copyright (C) 2019 gfuil 刘风广 <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package me.gfuil.bmap.lite.listener; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * 监听手机方向变化 */ public class MyOrientationListener implements SensorEventListener { private Context context; private SensorManager sensorManager; private Sensor sensor; private float lastX; private OnOrientationListener onOrientationListener; public MyOrientationListener(Context context) { this.context = context; } // 开始 public void start() { // 获得传感器管理器 sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); if (sensorManager != null) { // 获得方向传感器 sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } // 注册 if (sensor != null) {//SensorManager.SENSOR_DELAY_UI sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI); } } // 停止检测 public void stop() { sensorManager.unregisterListener(this); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { // 接受方向感应器的类型 if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { // 这里我们可以得到数据,然后根据需要来处理 float x = event.values[SensorManager.DATA_X]; if (Math.abs(x - lastX) > 1.0) { onOrientationListener.onOrientationChanged(x); } lastX = x; } } public void setOnOrientationListener(OnOrientationListener onOrientationListener) { this.onOrientationListener = onOrientationListener; } public interface OnOrientationListener { void onOrientationChanged(float x); } }