Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Checking for the Presence or Absence of a Sensor

Published? true
FormatLanguage: WikiFormat

Problem:

Before using an Android device for a sensor-based application, the programmer needs to ensure that the required sensor is supported by the device.

Solution:

Check for the availability of the sensor on the Android device.

Discussion:

SensorManager class is used to manage the sensors available on an Android device. So we require an object of this class:


        SensorManager deviceSensorManager = (SensorManager) getSystemService(SOME_SENSOR_SERVICE);


Then using the getSensorList() method we check for the presence of sensors of any type (accelerometer, gyroscope, pressure etc). If the list returned has size>0, implies that the sensor is present. A TextView is used to show the result: Sensor Present/Sensor Absent.


       List<android.hardware.Sensor> sensorList = deviceSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);

        if (sensorList.size() > 0) {
            sensorPresent = true;
            sensor = sensorList.get(0);
             
        }
        else
            sensorPresent = false;
        
        /* Set the face TextView to display sensor presence */
        face = (TextView) findViewById(R.id.face);
        
        if (sensorPresent)
            face.setText("Sensor present!");
        else
            face.setText("Sensor absent.");