How to Develop Android Location-aware Applications to Automate Location Tracking

There was a time when we had to carry a copy of a physical map for going to new places and still, it was hard to find. But then, smartphones were introduced with an inbuilt map service.

In this digital era, smartphone is common, and people carry their smartphones everywhere they go. But, what in it for us? The app makers? The developers?

You might have checked a GPS-based mobile application like Uber, Ola, and Taxi for Sure.

They are the apps with which, you can book a taxi from your smartphone.

And, when you open the Uber app, the screen displays your current location.

But how? How does it exactly fetch your current location?

Any guess?

Let us get it straight. It’s feasible with the help of Android location API.

Take Trackster for an example. It is a real-time phone tracking app that is solely developed to track kids, friends, or employees as per one’s needs. With this app, an employer can rest in peace knowing that his/her employees are at stationed position and the work is getting done.

download

At our app development center in India, we have integrated this feature for around 17+ times, so we know how exactly it works. We decided to write a step-by-step process so you, as a developer, can use it directly in your next project.

Let’s get started

First, open your Android Studio and create a new project under the file menu.

1
Next, select ‘Google Maps Activity’ in the following tab.

2

 

3

 

In the next step, create a new project on Google console. Go to console.developers.google.com and create a new project.

3

 

Once you create your project on the console, go to the ‘Library’ tab and enable Google Map Android API.

4

When Google Map API is enabled, switch to the ‘Credentials’ tab and create credentials from credentials option and put your API key in

‘debug/res/values/google_maps_api.xml’ 

and

‘release/res/values/google_maps_api.xml’

 

4

Code Integration

1 activity_maps.xml

Here, we’ll add SupportMapFragment for map and Button to get the present location.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="spaceo.mapdemo.MapsActivity" />
<Button
android:layout_margin="16dp"
android:layout_gravity="bottom|center"
android:id="@+id/btnMyLocation"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Direction" />
</FrameLayout>

2 MapsActivity.java

We’ll use one tracker for location updates.

tracker = new GPSTracker(this);

After tracker is used, it’s time for map initialization.

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setAllGesturesEnabled(true);
map.getUiSettings().setMapToolbarEnabled(false);
map.getUiSettings().setZoomGesturesEnabled(true);
map.setBuildingsEnabled(true);
map.setIndoorEnabled(true);
}
});
For marshmallow devices, we’ll need ACCESS_FINE_LOCATION runtime permission.

private void getLocation() {
if (!tracker.canGetLocation) {
if (Build.VERSION.SDK_INT >= 23) {
String[] PermissionsLocation = {android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION};
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(PermissionsLocation, REQ_LOCATION_PERMISSION);
} else
showLocationAlert();
} else
showLocationAlert();
} else setMyLocation();
}

If the Android location services is disabled, we’ll show an alert dialog for users to enable the Android location service in their device.

private AlertDialog locationAlertDialog;
private void showLocationAlert() {
if (null == locationAlertDialog)
locationAlertDialog = new AlertDialog.Builder(this, Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? android.R.style.Theme_Material_Light_Dialog_Alert : -1)
.setCancelable(false)
.setMessage("This demo application would like to access your location")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQ_OPEN_SETTING);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
locationAlertDialog.show();
}

3 GPSTracker.java

public final class GPSTracker implements LocationListener {
private final Context mContext;
private boolean isGPSEnabled = false;
private boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
|| Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
getLocation();
}
/**
* Function to get the user's current location
*
* @return
*/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("isGPSEnabled", "=" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
if (isGPSEnabled || isNetworkEnabled) {
this.canGetLocation = true;
location = null;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(location);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
@Override
public void onLocationChanged(Location location) {
if (location == null)
return;
this.location = location;
latitude = location.getLatitude();
longitude = location.getLongitude();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

If you have successfully implemented the process, you have integrated the automate location tracking and now it’s time to run the application.

Remember, location-based apps are the key value proposition for mobile devices. It means, its importance has already started increasing beyond smartphones. Now the transition has already stepped into watches and cars as well.

Android location API have many possibilities for your app idea and we already have a couple of success stories of integrating the location API into an app. We are a mobile app development company, and, as a matter of fact, we’ve already worked on the location-based projects. You can check our portfolio here.

If you want to download the entire source code, you can grab it from GitHub. We have also published it on GitHub so all the developers can directly use it.

This page was last edited on July 27th, 2018, at 1:52.
 
 

Have an App Idea?

Get your free consultation now