android 利用重力感应监测手机摇晃,做出相应反应

这个是利用手机摇晃,做出一定反应。具体功能自己开发
package com.ray.test;

import android.R.integer;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;

public class SensorTest extends Activity implements SensorListener{
// private SensorManager sensorMgr;

// Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

private float x, y, z,last_x,last_y,last_z;
private long lastUpdate;

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

SensorManager sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
}

public void onAccuracyChanged(int sensor, int accuracy) {
// TODO Auto-generated method stub

}

private static final int SHAKE_THRESHOLD = 5000;
//这个控制精度,越小表示反应越灵敏

public void onSensorChanged(int sensor, float[] values) {
// TODO Auto-generated method stub
if(sensor == SensorManager.SENSOR_ACCELEROMETER){
long curTime = System.currentTimeMillis();
//每100毫秒检测一次
if((curTime-lastUpdate)>100){
long diffTime = (curTime-lastUpdate);
lastUpdate = curTime;

x = values[SensorManager.DATA_X];

y = values[SensorManager.DATA_Y];

z = values[SensorManager.DATA_Z];
float speed = Math.abs(x+y+z-last_x-last_y-last_z)/diffTime*10000;
if(speed>SHAKE_THRESHOLD){
//这里写上自己的功能代码
setTitle("x="+(int)x+","+"y="+(int)y+","+"z="+(int)z);
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值