首先設定擷取Android手機的感應訊號
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
範例:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
view = new MySurfaceView(this);
setContentView(view);
}
再來取得sensor的種類,並註冊之
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
範例:
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
}
再者比較關鍵的部份,讀取各自的訊號。以下使用if else的方式來取得G-sensor和Orientation的訊號。
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// G-sensor的執行動作
}
if(event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
// Orientation的執行動作
}
範例:public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
view.onValueChanged(event.values);
}
if(event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
}
}
最後記得要在程式結束點取消Sensors的註冊範例:
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
沒有留言:
張貼留言