2011-11-30

在 Android 裡使用地磁感應器(Magnetic Field)

感應器的型別為 Sensor.TYPE_MAGNETIC_FIELD,用法同其他感應器。

main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <TextView
    android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>
MagneticActivity
public class MagneticActivity extends Activity implements SensorEventListener {

    private static final String TAG = "MagneticActivity";
    private SensorManager sensorMgr;
    private Sensor sensor;
    private TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.insert2Tv("onCreate...");
        this.sensorMgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        List<Sensor> list = this.sensorMgr.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
        if (list.isEmpty()) {
            this.insert2Tv("不支援地磁感應器");
        }
        else {
            this.sensor = list.get(0);
            this.insert2Tv("找到地磁感應器:" + this.sensor.getName());
        }
        this.insert2Tv("onCreated");
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (this.sensor != null) {
            this.insert2Tv("unregisterListener...");
            this.sensorMgr.unregisterListener(this, this.sensor);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.sensor != null) {
            this.insert2Tv("registerListener...");
            this.sensorMgr.registerListener(this, this.sensor,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        this.insert2Tv("目前地磁方向:X - " + event.values[0] + ", Y - "
                + event.values[1] + ", Z - " + event.values[2]);
    }

    private void insert2Tv(String msg) {
        if (this.tv == null) {
            this.tv = (TextView) this.findViewById(R.id.tv);
        }
        this.tv.setText(msg + "\n" + this.tv.getText().toString());
        Log.d(TAG, msg);
    }
}
地磁感應器要安裝到手機上才會運作。

沒有留言:

張貼留言