Creating a Barometer Application for Android
We continue our exploration of the sensors supported by the Android SDK with pressure sensor. To discover how to use this sensor, we are going to create a Barometer Application for Android.
As a reminder, a Barometer is a scientific instrument used in meteorology to measure atmospheric pressure. By using the data provided by the pressure sensor of Android devices, we are going to create our own Barometer Application.
Note that you can watch this tutorial in video on YouTube too :
Creating the User Interface
The User Interface for our Barometer Application will be really simple since we will display only the pressure value measure in text format. So, we define a TextView centered on the screen in our activity_main.xml layout file :
Getting values of the Atmospheric pressure
On Android, pressure data are accessed by registering to the updates of the pressure sensor of the device. So, we need to get an instance of the pressure sensor via the Sensor class and then registering a SensorEventListener object to be notified when values are updated :
Once the SensorEventListener is registered on the SensorManager service, the new value measure for the pressure will be sent via the onSensorChanged method. In this method, we will have to read the first index of the values array associated to the SensorEvent parameter to get the value measured for the atmospheric pressure.
Writing the Java code of the Main Activity
Next step is to use this code for the sensor in the Main Activity of our Barometer Application. We will register the pressure sensor on the SensorManager in the onCreate method of the MainActivity class. Then, we don’t forget to unregister our sensorEventListener instance from the SensorManager in the onPause method of the MainActivity. It will avoid to continue to be notified when our application will be paused and will save the battery of the device.
It gives us the following code for the MainActivity class :
Our Barometer Application in action
Once our Barometer Application is launched on an Android device, we have the following display :
You can also try our Barometer directly by downloading it on the Google Play Store :
To go further, we could store the data measured by the pressure sensor and then displaying them on a real time graph. If you are interested for that, tell me in comments and I will try to make that in a future tutorial.
To discover more tutorials on Android development, you can visit and subscribe to the SSaurel’s Channel :