package com.qianfeng.assistant.modules.other.utils;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
/**
* Created by Administrator on 16-3-29.
*/
public class AssistantSensorListener implements SensorEventListener {
private Sensor sensor;
private SensorManager manager;
private final long thresholdTime=300;
private long lastTime;
private long tempTime;
private final double thresholdSpeed=100;
private IShakeListener listener;
/**
* 记录传感器上一次的空间位置
*/
private float lastX,lastY,lastZ;
public AssistantSensorListener(Context context){
//获取传感器manager
manager= (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
if(manager!=null){
//获取默认的加速度传感器
sensor=manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(sensor!=null){
//注册传感器
manager.registerListener(this,sensor,Sensor.TYPE_ACCELEROMETER);
}
}
}
@Override
public void onSensorChanged(SensorEvent event) {
long currentTime=System.currentTimeMillis();
tempTime=currentTime-lastTime;
//控制刷新的频率
if( tempTime< thresholdTime){
return;
}
lastTime=currentTime;
float[] values=event.values;
float x=values[0];
float y=values[1];
float z=values[2];
LogUtils.d("onSensorChanged event", x + "," + y+","+z+";");
//计算三个坐标轴上的相对位移
float tempx=x-lastX;
float tempy=y-lastY;
float tempz=z-lastZ;
double speed=Math.sqrt(tempx*tempx+tempy*tempy+tempz*tempz)*1000/tempTime;
//重新记录位置
lastX=x;
lastY=y;
lastZ=z;
//如果速度达到100,即可认定手机正在摇动,用监听器回调出去
if(speed > thresholdSpeed && listener!=null){
listener.onShake(speed);
}
LogUtils.e("speed"+speed);
}
/**
* 设置摇一摇监听器
*
* @param listener 摇一摇监听器
*/
public void setShakeListener(IShakeListener listener){
this.listener=listener;
}
/**
*
* 注销系统服务
*/
public void unRegisterManager(){
if(manager!=null&&sensor!=null){
manager.unregisterListener(this);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/**
* 摇一摇接口
*/
public interface IShakeListener{
/**
* 正在摇动
*speed 摇动的速度
*/
void onShake(double speed);
}
}
本文标题:传感器AssistantSensorListener
链接分享:
http://cdweb.net/article/jhcjjo.html