安卓复习10
下面的代码通过手机的方向传感器显示方位角、倾斜角和滚动角在TextView
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView tv_value1;
private TextView tv_value2;
private TextView tv_value3;
private SensorManager sManager;
private Sensor mSensorOrientation;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取系统的传感器服务
sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensorOrientation = sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
//注册监听,SensorManager.SENSOR_DELAY_UI获取传感器状态和值的频率为低
sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
bindViews();
}
//绑定视图
private void bindViews() {
tv_value1 = (TextView) findViewById(R.id.tv_value1);
tv_value2 = (TextView) findViewById(R.id.tv_value2);
tv_value3 = (TextView) findViewById(R.id.tv_value3);
}
@Override
public void onSensorChanged(SensorEvent event) {
//使用Math.round()方法取整
tv_value1.setText("方位角:" + (float) (Math.round(event.values[0] * 100)) / 100);
tv_value2.setText("倾斜角:" + (float) (Math.round(event.values[1] * 100)) / 100);
tv_value3.setText("滚动角:" + (float) (Math.round(event.values[2] * 100)) / 100);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}