How to know if a sensor is present on my Android device?

有些话、适合烂在心里 提交于 2019-12-03 03:17:25

Your second line can be used for this:

boolean accelerometer;

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

if(accelerometer) 
{
.
.
}

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);

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.
}

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;
        }
    }

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
       }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!