Skip to content

Instantly share code, notes, and snippets.

@ufo22940268
Created December 6, 2012 23:08
Show Gist options
  • Save ufo22940268/4229310 to your computer and use it in GitHub Desktop.
Save ufo22940268/4229310 to your computer and use it in GitHub Desktop.
sensor
package com.example.android.skeletonapp;
/*
* @author octobershiner
* 2011 07 27
* SE.HIT
* 一个演示android加速度感应器的例子
* */
import java.util.Iterator;
import java.util.List;
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.util.Log;
public class SkeletonActivity extends Activity {
/** Called when the activity is first created. */
//设置LOG标签
private static final String TAG = "sensor";
private SensorManager sm;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.skeleton_activity);
//创建一个SensorManager来获取系统的传感器服务
sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
//选取加速度感应器
int sensorType = Sensor.TYPE_ACCELEROMETER;
/*
* 最常用的一个方法 注册事件
* 参数1 :SensorEventListener监听器
* 参数2 :Sensor 一个服务可能有多个Sensor实现,此处调用getDefaultSensor获取默认的Sensor
* 参数3 :模式 可选数据变化的刷新频率
* */
sm.registerListener(myAccelerometerListener,sm.getDefaultSensor(sensorType),SensorManager.SENSOR_DELAY_NORMAL);
}
/*
* -y
* +x -x
* +y
* */
final SensorEventListener myAccelerometerListener = new SensorEventListener(){
//复写onSensorChanged方法
public void onSensorChanged(SensorEvent sensorEvent){
if(sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
Log.i(TAG,"onSensorChanged");
//图解中已经解释三个值的含义
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
float threshold = 2;
float thresholdDouble = 3;
Log.i(TAG,String.format("x: %f, y: %f", x, y));
if (Math.abs(x) <= threshold && Math.abs(y) <= threshold) {
Log.i(TAG,"None");
} else {
if (Math.abs(x) > thresholdDouble && Math.abs(y) > thresholdDouble) {
if (x < 0 && y < 0) {
Log.i(TAG,"right up");
} else if (x < 0 && y > 0) {
Log.i(TAG,"right down");
} else if (x > 0 && y < 0) {
Log.i(TAG,"left up");
} else if (x > 0 && y > 0) {
Log.i(TAG,"left down");
}
} else {
if (Math.abs(x) > Math.abs(y)) {
Log.i(TAG, x > 0 ? "left" : "right");
} else {
Log.i(TAG, y > 0 ? "down" : "up");
}
}
}
}
}
//复写onAccuracyChanged方法
public void onAccuracyChanged(Sensor sensor , int accuracy){
Log.i(TAG, "onAccuracyChanged");
}
};
public void onPause(){
/*
* 很关键的部分:注意,说明文档中提到,即使activity不可见的时候,感应器依然会继续的工作,测试的时候可以发现,没有正常的刷新频率
* 也会非常高,所以一定要在onPause方法中关闭触发器,否则讲耗费用户大量电量,很不负责。
* */
sm.unregisterListener(myAccelerometerListener);
super.onPause();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment