温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

传感器AssistantSensorListener

发布时间:2020-07-22 03:33:57 来源:网络 阅读:459 作者:乐无莜 栏目:移动开发
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);
    }
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI