How to Build a SOS Mobile Application in Android Studio?
The SOS applications are basically advanced emergency apps that can rescue you and/or your loved ones if you and/or they find themselves in a life-threatening emergency situation and need immediate assistance. When you need some personal assistance, you can actually turn on your phone and can call or message someone for help. But in a life-threatening emergency like attack, sexual assault, robbery, harassment, accident, fire, birth assistance, we don’t have time to open our phone, instead, we need some accessibility methods by which we can reach out for help without actually operating the phone. In this article, we would be building such an application for android.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Can you think of some easiest ways of stimulating some functions in your phone, without actually turning ON your phone’s screen? One such way is by shaking your phone. We will be creating a service, and in that service, we would listen for a Shake Event by the phone. When we register a shake event i.e., when the user shakes the phone, we would send the user’s location with a predefined message to all the contacts which the user has previously added to the app. Now with every release of Android, Google has made some strict regulations regarding fetching of the User’s location, and also it is important when it comes to data security. And this makes it difficult to create such an SOS application for newer versions of Android.
- Runtime Permission Management,
- Populating ListView,
- Broadcast Receiver,
- Database Management in Android
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Creating the Contacts Module
Create a folder Contacts, in this, we will handle all the files which would populate the ListView by the contacts that the user selects to send messages at the time of emergency.
Step 2.1: Creating model class for Contact
Create a model class that will hold the data of Contact, mainly Name and Phone Number. Apart from the usual constructor and getters and setters, we have an additional validate(String) method. This method checks if the retrieved phone number is in the correct format(+91XXXXXXXXXX) or not. If not, then it converts the string and returns the formatted string. Below is the code for the ContactModel.java file.
Step 2.2: Creating a Database Helper class
We need to store all the contacts, the user selects, into a Database so that it is available every time the app needs it. We will populate the ListView with the help of this database and also at the time of sending messages, we will retrieve the contacts in a list from this database. Below is the code for the DbHelper.java file.
Step 2.3: Creating a CustomAdapter.java
In order to handle the data in ListView, we will need a Customised Adapter. We will add a LongClickListener on the LinerLayout so that whenever a user wants to delete an existing item from ListView he can simply long-press that item. And in return, we would show a dialog asking for confirmation. As the user confirms, we will also delete that item from the database too. Below is the code for the CustomAdapter.java file.
Step 2.4: item_user.xml
Layout file for each item in ListView.
Step 3: Creating the Service Module
This module would contain all the necessary functionality for shake detection, running services, and registering a Broadcast Receiver.
Step 3.1: Creating ShakeDetector class
Here we implement the SensorEventListener which is used for receiving notifications from the SensorManager when there is a new or change in sensor data. Now, in order to register the shake event, the G-Force by which the sensor experience when the user shakes the phone must be greater than 1G. This is because there may be cases when the phone might shake while in the pocket, or in the car, etc. And also to resolve this drawback we include a count mechanism that would count the number of shakes, i.e. if the user shakes the device 3 consecutive times, then we would register a shake event. And to do so the time between the two successive shakes should be minimum i.e. around 500ms. We will also make the shake count to zero after 3 seconds of inactivity. This would allow the user to again shake the phone to send messages. Below is the code for the ShakeDetector.java file.
Step 3.2: Creating the SensorService
Creating a sensor service. From the commencement of Android 6, Google has included some extra security checks regarding background services. Now handling of services is completely different as it was done previously.
Our main focus while building this app should be on how we can keep the service running even when the app is not running (even removed from the recent).
For service to run while the host application is Dead, is called Service to run in the background. And to make a service run in the background we need some extra permissions. In Android O and above we can’t have background service, instead, we can use the Foreground Services. Foreground services perform operations that are noticeable to the user.
A status bar warning with a priority of PRIORITY LOW or higher must be shown for each foreground operation. Users would be conscious that the app is running in the foreground and using machine resources in this manner. Unless the service is discontinued or withdrawn from the foreground, the message cannot be ignored.
If you start a service starts with the START STICKY return type, it will run in the background even if the host activity is not running in the foreground. If Android has to forcibly close a program due to a memory error or other reasons, the service will be restarted without the user’s intervention.
In order to make the user aware that the Shake event has been registered or say the messages have been delivered, we create a vibrate() method. This will make the phone vibrate in a defined wave format.
Now, in order to fetch the user location, we will use FusedLocationProviderClient. The FusedLocationProviderClient has a function named getCurremtLocation(). This method provides the current location of the user when asked for. But this method requires the mobile phone’s GPS to be turned ON. Otherwise, it will return a null location. From Android O and above, in order to fetch location or anything which would reveal the user’s location to the app, the location services or the GPS should be turned ON. So, that the user is aware of the location usages by the app.
Further, when we retrieve the location successfully, we Create a SMSManager object which will help us to send messages to all the contacts from the database. In case the user’s location services are not ON, we can generate a different message without the coordinates. So that one receiving the emergency message knows that the host device didn’t have location services on at that moment. He can then directly coordinate with the nearby Police department who can then track the person’s device location.
Till now whatever we have done will work until the activity is in Foreground or Running. But what when the user kills the application? Or locks the phone? For this, we create a BroadcastReceiver.
Below is the complete code for the SensorService.java file.
Step 3.3: Creating the Broadcast Receiver
Whenever a service is destroyed, the onDestroy method is called, and we will use that method to call a broadcast receiver before the service is actually destroyed.
The broadcast receiver in return again starts the service. And our problem is resolved!! The service now runs without the host activity in the background.
Below is the complete code for the ReactivateService.java file.
Step 4: Working with the MainActivity
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 5: Working with AndroidManifest.xml
- You can add options for personal assistance emergencies like a map that indicates nearby police stations, hospitals, cabs, etc.
- You create a logic that sends the user location every 1 or 2 minutes without the user shaking the device again.
- You can add voice or/and video recording functionality.
- Also, you can add a call to multiple or a single person at the time of shake.
- You can try to add OpenCellId, this will allow you to fetch the location of the nearest mobile tower. But again remember that in order to calculate the location you would require some device information(no GPS) and that would require your GPS or location services to be turned ON.
- Doors to changes in the UI are always open.
1. Allow the app to autostart, in order to use the app while the screen is off.
2. Remove any battery optimization constraints on the app. This might make Android kill the service.
3. Allow all the permissions, especially allow location permissions by Allowing the app to use the device location all the time. This would allow the service to use the device location when the shake event is registered.
GitHub Link: https://github.com/raghavtilak/SOS