您好,登錄后才能下訂單哦!
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)聽器回調(diào)出去 if(speed > thresholdSpeed && listener!=null){ listener.onShake(speed); } LogUtils.e("speed"+speed); } /** * 設(shè)置搖一搖監(jiān)聽器 * * @param listener 搖一搖監(jiān)聽器 */ 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); } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。