Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1078974
  • 博文数量: 403
  • 博客积分: 10272
  • 博客等级: 上将
  • 技术积分: 4407
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:22
文章分类

全部博文(403)

文章存档

2012年(403)

分类: 嵌入式

2012-03-10 16:39:52

package enent.jj;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;

public class Evnet1Activity extends Activity {
//检测摇动相关变量


private static final int FORCE_THRESHOLD = 350;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 3;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
private long mLastTime;
private float mLastX=-1.0f, mLastY=-1.0f, mLastZ=-1.0f;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);





// 获取传感器管理器
SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// 获取加速度传感器
Sensor acceleromererSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

// 定义传感器事件监听器
SensorEventListener acceleromererListener = new SensorEventListener() {

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//什么也不干
}

//传感器数据变动事件
@Override
public void onSensorChanged(SensorEvent event) {


//获取加速度传感器的三个参数
float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];

long now = System.currentTimeMillis();

if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}

if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(event.values[SensorManager.DATA_X] + event.values[SensorManager.DATA_Y] + event.values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (true) {
startRecord();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = event.values[SensorManager.DATA_X];
mLastY = event.values[SensorManager.DATA_Y];
mLastZ = event.values[SensorManager.DATA_Z];
}




}

};

//在传感器管理器中注册监听器
sm.registerListener(acceleromererListener, acceleromererSensor, SensorManager.SENSOR_DELAY_NORMAL);

}

// 开始
public void startRecord() {
Toast.makeText(getApplicationContext(), "yao",1).show();
}


}
阅读(1435) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~