<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="加速計實時數據" /> <TextView android:id="@+id/xcoor" android:text="X Coordinate: " android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/ycoor" android:text="Y Coordinate: " android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/zcoor" android:text="Z Coordinate: " android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
package com.example.HelloWorld; import android.app.Activity; import android.os.Bundle; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.widget.TextView; public class MyActivity extends Activity implements SensorEventListener{ private SensorManager sensorManager; TextView xCoor; // declare X axis object TextView yCoor; // declare Y axis object TextView zCoor; // declare Z axis object @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); xCoor=(TextView)findViewById(R.id.xcoor); // create X axis object yCoor=(TextView)findViewById(R.id.ycoor); // create Y axis object zCoor=(TextView)findViewById(R.id.zcoor); // create Z axis object sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE); // add listener. The listener will be MyActivity (this) class sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } // 當精度發生變化時調用 public void onAccuracyChanged(Sensor sensor,int accuracy){ } // 當sensor事件發生時候調用 public void onSensorChanged(SensorEvent event){ // check sensor type if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){ // assign directions float x=event.values[0]; float y=event.values[1]; float z=event.values[2]; xCoor.setText("X: "+x); yCoor.setText("Y: "+y); zCoor.setText("Z: "+z); } } @Override protected void onDestroy() { sensorManager.unregisterListener(this); super.onDestroy(); } }
運行效果以下: html
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
//傳感器精度改變時調用 public abstract void onAccuracyChanged (Sensor sensor, int accuracy) //傳感器獲取的數值改變時調用 public abstract void onSensorChanged (SensorEvent event)上面的示例中並無去具體化onAccuracyChanged()方法,而具體化了onSensorChanged()方法。