2010年10月9日星期六

獲取系統傳感器的信息, getSensorList()

Android系統提供多種類型的傳感器, 應用程序可以使用getSensorList()方法獲取系統傳感器的信息.

下面是一個例子, 首先擴展ListActivity創建一個Activity, 使用getSensorList()方法獲取系統傳感器的信息, 它的內容是一個可用傳感器(android.hardware.Sensor)的列表, 當任何一項被點擊, 它的詳細信息將顯示在對話框裡面.




(當運行在真正的設備時, 將顯示更多的傳感器.)

package com.AndroidSensor;

import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class AndroidSensor extends ListActivity {

List<Sensor> sensorList;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);

SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);

setListAdapter(new ArrayAdapter<Sensor>(this,
android.R.layout.simple_list_item_1, sensorList));
getListView().setTextFilterEnabled(true);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Sensor tSensor = sensorList.get(position);
String strSensor
= "Name: " + tSensor.getName()
+ "\nVersion: " + String.valueOf(tSensor.getVersion())
+ "\nVendor: " + tSensor.getVendor()
+ "\nType: " + String.valueOf(tSensor.getType())
+ "\nMax: " + String.valueOf(tSensor.getMaximumRange())
+ "\nResolution: " + String.valueOf(tSensor.getResolution())
+ "\nPower: " + String.valueOf(tSensor.getPower())
+ "\nClass: " + tSensor.getClass().toString();

new AlertDialog.Builder(this)
.setTitle("Title").setMessage(strSensor)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {}
}).show();
}
}


相關文章: 檢測加速度計(Accelerometer)的詳細數據, SensorEventListener()



沒有留言:

發佈留言