偵測SmartPhone或tablet所有Sensor資訊

1. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="" />
        </LinearLayout>
    </ScrollView>


</LinearLayout>

2. MainActivity.java

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 準備顯示資訊的UI 組建
final TextView tx1 = (TextView) findViewById(R.id.TextView01);
// 從系統服務中獲得感測器管理器
SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// 從感測器管理器中獲得全部的感測器列表
List<Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);
// 顯示有多少個感測器
tx1.setText("經檢測該手機有" + allSensors.size() + "個感測器,他們分別是:\n\n");
// 顯示每個感測器的具體資訊
for (Sensor s : allSensors) {

String tempString = "\n" + " 設備名稱:" + s.getName() + "\n" + " 設備版本:"
+ s.getVersion() + "\n" + " 供應商:" + s.getVendor() + "\n";
switch (s.getType()) {

case Sensor.TYPE_ACCELEROMETER:
tx1.setText(tx1.getText().toString() + " 加速度感測器 accelerometer"
+ tempString + "\n");
break;
case Sensor.TYPE_GYROSCOPE:
tx1.setText(tx1.getText().toString() + " 陀螺儀感測器gyroscope"
+ tempString + "\n");
break;
case Sensor.TYPE_LIGHT:
tx1.setText(tx1.getText().toString() + " 環境光線感測器light"
+ tempString + "\n");
break;
case Sensor.TYPE_MAGNETIC_FIELD:
tx1.setText(tx1.getText().toString() + " 電磁場感測器magnetic field"
+ tempString + "\n");
break;
case Sensor.TYPE_ORIENTATION:
tx1.setText(tx1.getText().toString() + " 方向感測器orientation"
+ tempString + "\n");
break;
case Sensor.TYPE_PRESSURE:
tx1.setText(tx1.getText().toString() + " 壓力感測器pressure"
+ tempString + "\n");
break;
case Sensor.TYPE_PROXIMITY:
tx1.setText(tx1.getText().toString() + " 距離感測器proximity"
+ tempString + "\n");
break;
case Sensor.TYPE_TEMPERATURE:
tx1.setText(tx1.getText().toString() + " 溫度感測器temperature"
+ tempString + "\n");
break;
default:
tx1.setText(tx1.getText().toString() + tempString + "\n");
break;

}
}
}
}

沒有留言: