2

I was reading about Sensors in Android and ways how to check their availability on the device. But I faced with kind of contradiction. Official Android Guide says that one should use SensorManager as follows:

private SensorManager mSensorManager;
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

if (mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) {
    // device has Accelerometer sensor...
}

to obtain Sensor entity and check whether it's null or not. But as far as I understand there is another (similar?) way to do it using PackageManager instead:

private PackageManager mPackageManager;
mPackageManager = mContext.getPackageManager();

if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER)) {
    // device has Accelerometer sensor...
}

I would not hesitate to use the approach from the official guide, but I found this Quiz that says the correct way is via PackageManager:

Answer. The correct answer is Answer 1, the version that uses PackageManager.

SensorManager and Sensor are part of Android Sensor Framework and are used for direct access and acquisition of raw sensor data. These classes do not provide any method like hasSystemFeature() which is used for evaluation of system capabilities.

Android defines feature IDs, in the form of ENUMs, for any hardware or software feature that may be available on a device. For instance, the feature ID for the compass sensor is FEATURE_SENSOR_COMPASS.

If your application cannot work without a specific feature being available on the system, you can prevent users from installing your app with a element in your app’s manifest file to specify a non-negotiable dependency.

However, if you just want to disable specific elements of your application when a feature is missing, you can use the PackageManager class. PackageManager is used for retrieving various kinds of information related to the application packages that are currently installed on the device.

So my question is: is there any difference in which way I do this? Should I prefer SensorManager or PackageManager? Why? Should or Can I use them both like

if(mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) && 
    mPackageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER)) {
    // device (surely?) has Accelerometer sensor...
}

?

Thank you all in advance!

Community
  • 1
  • 1
Alex
  • 31
  • 7

0 Answers0