Android 所有的感應器使用統一的 API - SensorManager 與 Sensor,以 Sensor.TYPE_xxx 做識別,可以用 Sensor.TYPE_ALL 取得所有支援的感應器。
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" > <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>LightSensorActivity
public class LightSensorActivity extends Activity implements SensorEventListener { private static final String TAG = "LightSensorActivity"; private SensorManager mgr; private Sensor sensor; private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.d(LightSensorActivity.TAG, "onCreate..."); // Android 所有的感應器的統一介面 this.mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE); // 下面這種方式會取道一個沒有作用的感應器 // this.sensor = this.mgr.getDefaultSensor(Sensor.TYPE_LIGHT); // 取得所有感應器 List<Sensor> list = this.mgr.getSensorList(Sensor.TYPE_ALL); for (Sensor s : list) { this.insert2Tv("支援的感應器:" + s.getName()); } // 取得亮度感應器 list = this.mgr.getSensorList(Sensor.TYPE_LIGHT); // 我的手機啊,你為什麼不支援亮度感應器 if (list.isEmpty()) { String msg = "不支援亮度感應器"; Log.e(TAG, msg); this.insert2Tv(msg); return; } this.sensor = list.get(0); } @Override protected void onResume() { super.onResume(); Log.d(LightSensorActivity.TAG, "registerListener..."); // 一定要在這註冊 if (this.sensor != null) { this.mgr.registerListener(this, this.sensor, SensorManager.SENSOR_DELAY_NORMAL); } } @Override protected void onPause() { super.onPause(); Log.d(LightSensorActivity.TAG, "unregisterListener..."); // 一定要在這解註冊 if (this.sensor != null) { this.mgr.unregisterListener(this, this.sensor); } } @Override public void onSensorChanged(SensorEvent event) { String msg = "現在的亮度是 " + event.values[0] + " Lux"; Log.d(LightSensorActivity.TAG, msg); this.insert2Tv(msg); } @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()); } }亮度感應器要安裝到手機上才會運作。
沒有留言:
張貼留言