The use of sensors is mostly found in fitness and exercise apps for monitoring the users physical performance. But sensors can be used in every app to improve UI/UX. In this article I will share a different perspective by using the accelerometer to reload the current activity when the user intentionally shuffles the phone. This would mean that we do not have to add the reload button which consumes space and this would result in having more space to display the apps main features or content. We will also learn how to implement the fingerprint scanner which makes it easier for users to login.
Article Content Overview
- Use accelerometer to reload the current activity.
- Fingerprint Sensor.
- Full code.
Prerequisites and requirements for this article.
- Android Studio.
- A device with fingerprint sensor (scanner)and accelerometer sensor.
Using the Accelerometer Sensor.
An accelerometer measures the acceleration of the phone, this enables the sensor to detect changes in orientation. We will use the accelerometer sensor to reload the current activity when the user intentionally shuffles the phone.
Import the following classes.
Below I have listed and explained the sensor framework classes we will be using.
SensorManager: this class is used to create an instance of the sensor service and it also provides methods for accessing and listing sensors, registering and unregistering event listeners.
Sensor: this class is used to create an instance of a specific sensor.
SensorEvent: this class is used by the system to create a sensor event object which provides information about a sensor event.
SensorEventListener: This interface is used to create two callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.
Checking for availability of the sensor.
Before using any sensor ensure that the user’s device has the sensor you want to use. Below we check the availability of the accelerometer sensor.
Reloading the activity.
In the code below we reload the activity when the user shuffles the phone and implement methods of the SensorEventListener interface.
When you are done using the sensor listener ,unregister it to save the users battery as it would continue to collecting data if it is not unregistered. Use the onPause() method to unregister a listener.
You can get the full code here.