main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>OrientationActivity
public class OrientationActivity extends Activity implements SensorEventListener { private static String TAG = "OrientationActivity"; 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_ORIENTATION); if (list.isEmpty()) { this.insert2Tv("不支援傾斜感應器"); } else { this.sensor = list.get(0); this.insert2Tv("取得傾斜感應器:" + this.sensor.getName()); } this.insert2Tv("onCreated"); } @Override protected void onResume() { super.onResume(); if (this.sensor != null) { this.insert2Tv("registerListener..."); this.sensorMgr.registerListener(this, this.sensor, SensorManager.SENSOR_DELAY_NORMAL); } } @Override protected void onPause() { super.onPause(); if (this.sensor != null) { this.insert2Tv("unregisterListener..."); this.sensorMgr.unregisterListener(this, this.sensor); } } @Override public void onSensorChanged(SensorEvent event) { // 方位角,就是手機頭的朝向,北為0,東為90,餘類推,實做結果不準 // float val = event.values[0]; // 南北向旋轉,手機水平放置螢幕朝向上(0)、頭朝上(-90) // 頭向下(90)、水平放置螢幕朝向下(-180/180) // float val = event.values[1]; // 東西向旋轉,手機水平放置螢幕朝向上(0)、向右翻螢幕朝右(-90) // 向左翻螢幕朝左(90)、水平放置螢幕朝向下(0) // float val = event.values[2]; this.insert2Tv("方位角:" + event.values[0] + "南北向:" + event.values[1] + "東西向:" + event.values[2]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } 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); } }傾斜感應器要安裝到手機上才會運作。
沒有留言:
張貼留言