How to Build an Android Location Tracker App - Hive Programmers
Greetings to my favorite Science community online, StemSocial.
It's @skyehi and I'm excited to be back on a weekend to continue my series on Android App development tutorials for beginners.
I'm really proud to say that we have covered some significant ground on our series. For almost a month we've been building cools Apps. I'm hopeful that people that have followed the tutorial till date have greatly improved their Android App development and programming skills.
Today's App tutorial is going to be a location based on. In previous blogs, we built a Map and a GPS application. Now we're going to build a location tracker application.
Original Image Source by kuszapro from Pixabay
Like I made mention in previous blogs, your ability to build very useful Apps as a developer is a really great factor to your success. Imagine having to lose or misplace your Smart phone and you badly want to know where it is.
Or an even more realistic example; I'm pretty sure you know one of the most popular messaging App in the world called "WhatsApp Messenger".
This messaging App has a location tracker where users can get their own location and share that location with friends and family. This could be a really useful tool when you want your friend or loved one to know your exact location.
My brother and I used a location tracker to go visit a friend of his since we weren't familiar with the exact place that friend was.
Long story short, I'm really excited to be sharing this tutorial blog with my readers and followers because I know how useful a location tracker App can be in certain situations.
Without wasting anymore time, let's get started with our App shall we
Creating a New Project in Android Studio
Building the location tracker app in Android Studio will be an exciting project and would involve integrating location services and a few UI elements.
So guys, by the end of this tutorial, we will have an app that not only tracks your location but also allows you to share it with others via SMS and email.
The first thing to do is to open Android Studio and click "create a new project" . Now guys if you haven't had Android studio and Java Development Kit, JDK installed on you PC, please do that to be able to go through with this tutorial.
If you're having troubles downloading the softwares or installing them on your PC, please let me know in the comments
When creating a new project, you can choose the App name and package name. The package name is a unique identify of your App so that it is distinguished from other Apps.
Two different Apps cannot have the same package name so guys I'll recommend getting a unique package name. Also the more unique your App name is, the higher your chance of not getting your App confused with other Apps.
Most of the Apps you plan on developing may already have similar types on the Google Play store so a unique name really helps.
As usual, I'll recommend choosing an empty activity as template for our App project. Also guys, we're still writing codes in Java for the beginner's tutorials so please ensure that Java is the selected programming language and not Kotlin.
When you're satisfied with the project setup, click the finish button and Android Studio will prepare your project for you.
Adding Location and Internet Permissions
Alright guys, before we work on the frontend or User interface of our app, we need to request a couple of permissions inside the AndroidManifest.xml
file.
Our App will be able to do two things, gain the location of the user and share the location. This means that the App would need access to both the location and internet service of the Android Device.
This is why it's important to request permission for these two services in the Manifest file.
Here's how your code should look like
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Designing our User Interface
It's finally time for the frontend design of our App. This is the part of the App the user will interact with. Since it's tutorial for beginners, I wouldn't want to create too complicated an App.
The location tracker app would need just two primary elements, a Button
for triggering location sharing and a TextView
to display the coordinates.
We'll be working on our App design inside the activity_main.xml
file.
Here's how your code should look like
<Button
android:id="@+id/btnShareLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share Location"
android:onClick="shareLocation" />
<TextView
android:id="@+id/tvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location: " />
Step 4: Implement Location Tracking in Java
It's time for the main work or logic of our App. This is going to be a marathon code like the previous ones, so buckle up guys.
We'll be writing the entire logic code inside the MainActivity.java
file. There are two main things we'll be doing; we'll set up the location services and also handle the button click event.
The code will also include the logic for sharing the current location via SMS and email. In the future with more advanced tutorials, we'll rebuild this App and include more features like sharing on social platforms and live video of the user.
Here's how your code should look like guys.
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private LocationListener locationListener;
private TextView tvLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocation = findViewById(R.id.tvLocation);
// Initialize location manager and listener
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// Update UI with new location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
tvLocation.setText("Location: " + latitude + ", " + longitude);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
// Check for location permissions
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Request location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
// Request permissions if not granted
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
// Button click event for sharing location
public void shareLocation(View view) {
// Get the current location
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
double latitude = lastKnownLocation.getLatitude();
double longitude = lastKnownLocation.getLongitude();
// Prepare location string
String locationString = "Latitude: " + latitude + ", Longitude: " + longitude;
// Share via SMS
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.putExtra("sms_body", locationString);
startActivity(smsIntent);
// Share via Email
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My Location");
emailIntent.putExtra(Intent.EXTRA_TEXT, locationString);
startActivity(emailIntent);
}
}
}
In the code I just wrote, I was able to include the logic to retrieve the current location and share it via SMS and email.
If you would notice, I included an SMS intent which opens the default messaging app with the location details, and the email intent creates an email with the location details as the body.
When your email App opens, the only thing you would add is the recipient email address and any extra information you want to send.
Running the App
Congratulations guys, we just finished another very good App. It's time to click that run button and see your first ever Location tracker App.
When the App launches, the textview will show you your current coordinates and you can click the button to share the location either via SMS or email.
You can run the App on your physical Android device or an emulator. Just remember to make sure USB Debugging is turned on, for your Android phone to be able to launch the App.
Thank you so much for taking the time to read today's post. I hope you enjoyed this tutorial as always. If you have any issues running the App, writing the code or even installing Android Studio and JDk, please let me know in the comments.
Have a lovely day and catch you next time on StemSocial. Goodbye 👨💻
You Can Follow Me @skyehi For More Like This And Others
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
Thanks for including @stemsocial as a beneficiary, which gives you stronger support.