Home » Android » android detect is gyroscope available

android detect is gyroscope available

Posted by: admin June 15, 2020 Leave a comment

Questions:

How can I detect whether the android device has gyroscope? Currently I’m using the following method to detect whether gyroscope is available. If gyroscope not available, then use accelerometer.

SensorManager mgr = (SensorManager) getSystemService(SENSOR_SERVICE);
        List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);
        for (Sensor sensor : sensors) {
            Log.i("sensors",sensor.getName());
           if(sensor.getName().contains("Gyroscope")){
               try{
                mSensorManager.registerListener(this,
                           mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
                           SensorManager.SENSOR_DELAY_FASTEST);
                return;
               }catch(Exception e){
               }
           }
        }
        mSensorManager.registerListener(this,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_FASTEST);

However some of my app users complaint they can’t use gyroscope. Is there any problem with the code?

How to&Answers:

You can simply use the Package Manager’s System features to check if the device has a gyroscope in it:

PackageManager packageManager = getPackageManager();
boolean gyroExists = packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_GYROSCOPE);

Your current code may not work on some devices as the sensor name is not guaranteed to contain Gyroscope in it.

Answer:

Use this:

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if(mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null)
{

         // Sensor FOUND
}
else
{
        //Sensor NOT FOUND
}

Answer:

You should use

sensor.getType() == Sensor.TYPE_GYROSCOPE

in place of your current sensor.getName().contains("Gyroscope") to determine if the sensor is a Gyroscope.

Answer:

This is my method:

public static boolean existGyroscope(Context ctx){
    SensorManager mSensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
    if(mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null){
        return true;
    }else{
        return false;
    }
}

used in all my apps.