Android 学习笔记(九):重力感应器
在Android中,所有传感器都要通过SensorMannager来访问,
然后调用getSystemService(SENSOR_SERVICE)方法得到手机的传感器管理对象,
onSensorChanged(SensorEvent se)在传感器值更改时调用,
使用传感器必须调用registerListener(SensorEventListener listener, Sensor sensor, int rate)方法注册,
感应器有3个方向float类型的值,x,y,z,取值范围在-10到10之间,
手机屏幕向上(z轴朝天)水平放置的时侯,x=0,y=0,z=10
手机屏幕向下(z轴朝地)水平放置的时侯,x=0,y=0,z=-10
手机屏幕向左(x轴朝天)的时候,x=10,y=0,z=0
手机竖直(y轴朝天)向上的时候,x=0,y=10,z=0
代码:
PS:在XML文件中有个TextView,用来显示重力感应器的值,
[java] public class TestActivity extends Activity {
TextView textView;
float x,y,z;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView=(TextView) findViewById(R.id.textView);
//获得重力感应硬件控制器
SensorManager sm=(SensorManager) this.getSystemService(SENSOR_SERVICE);
Sensor sensor=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//添加重力感应侦听,并实现其方法,
SensorEventListener sel=new SensorEventListener(){
public void onSensorChanged(SensorEvent se) {
x=se.values[SensorManager.DATA_X];
y=se.values[SensorManager.DATA_Y];
z=se.values[SensorManager.DATA_Z];
textView.setText("x="+(int)x+"y="+(int)y+"z="+(int)z);
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
};
//注册Listener,SENSOR_DELAY_GAME为检测的精确度,
sm.registerListener(sel, sensor,SensorManager.SENSOR_DELAY_GAME);
}
public class TestActivity extends Activity {
TextView textView;
float x,y,z;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView=(TextView) findViewById(R.id.textView);
//获得重力感应硬件控制器
SensorManager sm=(SensorManager) this.getSystemService(SENSOR_SERVICE);
Sensor sensor=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//添加重力感应侦听,并实现其方法,
SensorEventListener sel=new SensorEventListener(){
public void onSensorChanged(SensorEvent se) {
x=se.values[SensorManager.DATA_X];
y=se.values[SensorManager.DATA_Y];
z=se.values[SensorManager.DATA_Z];
textView.setText("x="+(int)x+"y="+(int)y+"z="+(int)z);
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
};
//注册Listener,SENSOR_DELAY_GAME为检测的精确度,
sm.registerListener(sel, sensor,SensorManager.SENSOR_DELAY_GAME);
}
当然,也可以用SensorEventListener接口来实现,
感应器在模拟器中是不能测试的,下面是真机测试效果,
摘自 柒尐狐的专栏
补充:移动开发 , Android ,