總網頁瀏覽量

2013年4月14日 星期日

SensorManager

SensorManager是手機平板電腦特有的功能


本文先說明加速度感測器:
加速度感測器顯示手機受到加速度的方向
分成X Y Z三個方向

將手機平躺著那麼X 與Y加速度趨近於零
Z加速度為9.8m/s^2

如果將手機直立Y加速度為9.8m/s^2
將手機橫立X軸加速度為9..8m/s^2

只是單純旋轉手機,不出力那麼所受的合力為9.8m/s^2




public class MainActivity extends Activity {
private SensorManager mgr;
private TextView info;
private Sensor sensor;
private MyListener listener;
private int nowz = -500, nowx, initx;
private float maxx;
private boolean isPull;
private int iscast = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

info = (TextView) findViewById(R.id.info);

mgr = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> list = mgr.getSensorList(Sensor.TYPE_ALL);

// for (Sensor sensor: list){
// info.append(sensor.getName() + ":" +
// sensor.getMaximumRange() + ":" +
// sensor.getResolution() + "\n"
// );
// }

//
sensor = mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//
// sensor = mgr.getDefaultSensor(Sensor.TYPE_ORIENTATION);

// sensor = mgr.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
// sensor = mgr.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
// sensor = mgr.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
listener = new MyListener();

}

@Override
protected void onResume() {
super.onResume();
mgr.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
super.onPause();
mgr.unregisterListener(listener);
}

private class MyListener implements SensorEventListener {

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

}

@Override
public void onSensorChanged(SensorEvent event) {
float[] data = event.values;
float x = data[0] * 10, z = data[2] * 100;
// info.setText(data[0]+"\n"+data[2]);

if (z < nowz) {


if (iscast == 0) {
Log.i("log", "以拉釣竿");
nowz = 990;
iscast = 1;
}

}

if (z > nowz) {
if (iscast == 1) {
if (x < 0) {

maxx = (Math.abs(1-x/10))*5;
Log.i("log", "z"+z + " x"+x);
info.setText("" + maxx);
iscast = 3;
}
}
maxx = 0;
initx = -20;
nowz = -500;

}

// if (z < nowz) {
// nowz = (int) z * 10;
// initx = (int) x;
// isPull = true;
// } else {
// isPull = false;
// if (x < initx) {
// int dx = (int) (Math.abs(x - initx));
// if (dx > maxx) {
// maxx = dx;
// info.setText("Power:" + maxx);
// }
// } else {
// nowz = 999;
// maxx = 0;
// }
// }
}}}




SensorManager.getOrientation();

沒有留言:

張貼留言