手机摇一摇 功能


原理:手机系统有传感器,调用手机传感器,并让手机振动

public abstract class ShakeListener implements SensorEventListener{

    private int duration = 100;//采样时间间隔

    private long lastTime;
    private float lastPointX;//上一个点的x轴的加速度信息
    private float lastPointY;
    private float lastPointZ;

    private float shake;//单次增量
    private float totalShake;//总增量
    private float swithValue = 100;//判断是否摇晃手机的最大值

    public ShakeListener(){
        init();
    }

    private void init(){
        lastTime = 0;
        lastPointX = 0;
        lastPointY = 0;
        lastPointZ = 0;
        shake = 0;
        totalShake = 0;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(lastTime == 0){
            lastTime = System.currentTimeMillis();
            lastPointX = event.values[SensorManager.DATA_X];
            lastPointY = event.values[SensorManager.DATA_Y];
            lastPointZ = event.values[SensorManager.DATA_Z];
        }else{
            long currentTime = System.currentTimeMillis();
            if(currentTime - lastTime > duration){
                //第二个点
                float x = event.values[SensorManager.DATA_X];
                float y = event.values[SensorManager.DATA_Y];
                float z = event.values[SensorManager.DATA_Z];

                //每次传入的数据都存在微小的变动
                float dx = Math.abs(x - lastPointX);
                float dy = Math.abs(y - lastPointY);
                float dz = Math.abs(z - lastPointZ);

                if(dx < 1){
                    dx = 0;
                }

                if(dy < 1){
                    dy = 0;
                }

                if(dz <1){
                    dz = 0;
                }
                shake = dx + dy + dz;

                if(shake == 0){
                    //处于静止状态
                    init();
                }

                totalShake += shake;

                if(totalShake > swithValue){
                    //说明是在摇晃手机
                    //机选一注彩票,并且有震动
                    shakeCrateLottery();
                    init();
                }else{
                    lastTime = System.currentTimeMillis();
                    lastPointX = event.values[SensorManager.DATA_X];
                    lastPointY = event.values[SensorManager.DATA_Y];
                    lastPointZ = event.values[SensorManager.DATA_Z];
                }

            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public abstract void shakeCrateLottery();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值