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){
//獲取默認(rèn)的加速度傳感器
sensor=manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(sensor!=null){
//注冊(cè)傳感器
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+";");
//計(jì)算三個(gè)坐標(biāo)軸上的相對(duì)位移
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;
//如果速度達(dá)到100,即可認(rèn)定手機(jī)正在搖動(dòng),用監(jiān)聽(tīng)器回調(diào)出去
if(speed > thresholdSpeed && listener!=null){
listener.onShake(speed);
}
LogUtils.e("speed"+speed);
}
/**
* 設(shè)置搖一搖監(jiān)聽(tīng)器
*
* @param listener 搖一搖監(jiān)聽(tīng)器
*/
public void setShakeListener(IShakeListener listener){
this.listener=listener;
}
/**
*
* 注銷系統(tǒng)服務(wù)
*/
public void unRegisterManager(){
if(manager!=null&&sensor!=null){
manager.unregisterListener(this);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/**
* 搖一搖接口
*/
public interface IShakeListener{
/**
* 正在搖動(dòng)
*speed 搖動(dòng)的速度
*/
void onShake(double speed);
}
}
本文名稱:傳感器AssistantSensorListener
標(biāo)題網(wǎng)址:
http://weahome.cn/article/jhcjjo.html