Android Sensor重力感应

1、定义变量

private SensorManager mSensorManager = null;
private Sensor mSensor = null;
private SensorEventListener mSensorEventListener = null;
private long lastUpdate = 0;
private float last_x,last_y,last_z;
private final float SHAKE_THRESHOLD = 800f;

2、初始化变量

private void initSensor(){
	mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	if(mSensorManager != null){
		mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		mSensorEventListener = new SensorEventListener() {
			@Override
			public void onSensorChanged(SensorEvent event) {
				// TODO Auto-generated method stub
				long curTime = System.currentTimeMillis();
				// 每100毫秒检测一次
				if ((curTime – lastUpdate) > 100) {
					long diffTime = (curTime – lastUpdate);
					lastUpdate = curTime;

					float x = event.values[SensorManager.DATA_X];
					float y = event.values[SensorManager.DATA_Y];
					float z = event.values[SensorManager.DATA_Z];

					float speed = Math.abs(x + y + z – last_x – last_y
					- last_z)
					/ diffTime * 10000;
					Log.i("speed", "speed=" + speed);
					if (speed > SHAKE_THRESHOLD) {
						//do something相应的处理
					}
					last_x = x;
					last_y = y;
					last_z = z;
				}
			}

			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// TODO Auto-generated method stub
			}
		};
	}
}

3、注册、取消注册监听

@Override
protected void onResume() {
	if(mSensorManager != null){
		mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
	}
	super.onResume();
}

@Override
protected void onPause() {
	if(mSensorManager != null){
		mSensorManager.unregisterListener(mSensorEventListener);
	}
	super.onPause();
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

原创博客,转载请标明出处:http://www.geekapp.cn/archives/173.html
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇