Android detects an available gyroscope

How to determine if an android device has a gyroscope? I am currently using the following method to determine if a gyro is available. If a gyroscope is not available, use an 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 complaints from application users cannot use the gyroscope. Are there any problems with the code?

+4
source share
4 answers

You can simply use the functions of the System Manager Package Manager to check if it 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 will not contain Gyroscope .

+12
source

Use this:

 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if(mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null) { // Sensor FOUND } else { //Sensor NOT FOUND } 
+7
source

You have to use

 sensor.getType() == Sensor.TYPE_GYROSCOPE 

instead of the current sensor.getName().contains("Gyroscope") to determine if the sensor is a gyroscope.

+1
source

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

0
source

Source: https://habr.com/ru/post/1489025/


All Articles