May 11, 2011

List of available sensors on Android

You can obtain the list of available sensors on your device by calling sensonManager.getSensorList() and providing the type Sensor.TYPE_ALL as a parameter. Find below a full example.




main.xml


    

main.java
package com.blog.sensorslist;

import java.util.List;

import android.app.ListActivity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.main);
        
        // create new SensorManager
        SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        // get all sensors of all types
        List sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
        // list of all sensor types
        String[] sensorTypes = new String[]{"","ACCELEROMETER", "MAGNETIC_FIELD", 
          "ORIENTATION", "GYROSCOPE", "LIGHT", "PRESSURE","TEMPERATURE", 
          "PROXIMITY", "GRAVITY", "LINEAR_ACCELERATION", "ROTATION_VECTOR"};
        
        // array for ListAdapter
        String[] infoList = new String[sensorList.size()];
        
        for (int i =0; i < sensorList.size(); i++){
         Sensor currentSensor = sensorList.get(i);
         infoList[i] = "Sensor Name: "+ currentSensor.getName() +"\n" +
             "Vendor: "+ currentSensor.getVendor() + "\n" +
             "Version: "+ currentSensor.getVersion()+ "\n"+
             "Type: "+ currentSensor.getType() + " - "+sensorTypes[currentSensor.getType()]+ "\n"+
             "Maximum Range: "+ currentSensor.getMaximumRange()+ "\n"+
             "Power (mA):"+ currentSensor.getPower()+ "\n"+
             "Resolution: "+ currentSensor.getResolution();              
        }
        // setting the ListAddapter
        setListAdapter(new ArrayAdapter(this, R.layout.main, infoList));
    }
}

0 comentarii:

Post a Comment