Search code examples
androidaccelerometer

How to determine if an Android device has an Accelerometer?


I want to check if an Android device has an accelerometer or not so that I can put a toast message saying that the game won't work properly on the current device if there isn't an accelerometer. I am looking for something like this:

if(DEVICE_HAS_ACCELEROMETER == false){
Toast.makeText(context,"No Accelerometer Found.",Toast.LENGTH_LONG).show();
}

If you can fill in the DEVICE_HAS_ACCELEROMETER part, that would do the job.

PS: I am not in an activity.


Solution

  • SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    if (accelerometerSensor != null)
    {
        // Device has Accelerometer
    }