14

i would like to know if a sensor (for exemple the accellerometer) is present on my Android device.

I am dealing with the SensorManager class. Here is the code I am using:

sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorMgr.registerListener(this,sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),1);

Thank you.

Miloš
  • 17,005
  • 46
  • 137
  • 240

5 Answers5

30

take a look in here:

http://developer.android.com/reference/android/content/pm/PackageManager.html

if think you need to do that:

PackageManager manager = getPackageManager();
boolean hasAccelerometer = manager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);
Sam Felix
  • 1,279
  • 1
  • 10
  • 22
14

Here is recomendation from developer.android.com: http://developer.android.com/guide/topics/sensors/sensors_overview.html#sensors-identify

You can determine whether a specific type of sensor exists on a device by using the getDefaultSensor() method and passing in the type constant for a specific sensor. If a device has more than one sensor of a given type, one of the sensors must be designated as the default sensor. If a default sensor does not exist for a given type of sensor, the method call returns null, which means the device does not have that type of sensor.

private SensorManager mSensorManager;
...
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){
  // Success! There's a magnetometer.
}
else {
  // Failure! No magnetometer.
}
DmitryDzz
  • 376
  • 3
  • 7
14

Your second line can be used for this:

boolean accelerometer;

accelerometer = sensorMgr.registerListener(this,sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

if(accelerometer) 
{
.
.
}
Milos Cuculovic
  • 1,207
  • 3
  • 17
  • 28
3

Since I get a API9 required error, I use instead:

    SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    List<Sensor> deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
    for (int i = 0; i< deviceSensors.size(); i++) {
        if (deviceSensors.get(i).getType() == Sensor.TYPE_PRESSURE) {
            mHasBarometer = true;
            break;
        }
    }
Gunnar Bernstein
  • 5,478
  • 1
  • 39
  • 60
0

I use the following code:

        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
       if( sensorManager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD).size() > 0)
       {
           //sensor exist
       }
       else
       {
           //disable feature
       }
farhad.kargaran
  • 1,932
  • 1
  • 18
  • 27