You are on page 1of 23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

DROID APP DEVELOPMENT


NOW TRENDING:
CHALLENGE FOR BEGINNERS

ANDROID

IOS (SWIFT)

STUDENT HOMEWORK HELP

ANDROID RECORD AND UPLOAD VIDEO TO SERVER USING RETROFIT 2

TIPS

ANDROID STUDENT PROJECT IDEAS

APPS FROM $1

FORUM

Search the site

Home Android
Android Real-time User Location Tracking Using Google Map API v2

ANDROID REAL-TIME USER


LOCATION TRACKING
USING GOOGLE MAP API V2
Henry

September 26, 2016

Android

6 Comments

In this
tutorial, we
are going to
learn how to
implement
Android Realtime user

EMAIL SUBSCRIPTION
Enter your email address:

location
tracking using
Google Map
API v2.
Tracking user

Subscribe
Delivered by FeedBurner

location can
be beneficial when you want to record the distance and route a user
has gone through during exercise or other activities. Based on the
distance, you can calculate other parameters and present a

LIKE US ON
FACEBOOK

meaningful and concise result to the user.


https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

1/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

Android real-time user location tracking using Google Map API v2 are
usually use in sports and social networking apps.

Inducesmile
Megustaestapgina

If you are looking for a way to draw path between two points on
Google Map or to measures the distance and duration between
two points, I will suggest you first read my posts on these topics.

Selprimerodetusamigosenindicarquele
gustaesto.

WHAT WE ARE GOING TO ACHIEVE


1. Create and load a Google Map
2. Create a Background Service that will listener to
onLocationChange events
3. Send the location data to a Local Broadcast Receiver
4. Update the UI Map View using the overlay Polyline to draw route
path.
Before we start it is important that that we understand what we are
planning to achieve in this tutorial. I have add some screen-shot
from this tutorial

APP
SCREENSHOT

RECENT POSTS
Android Mobile Food Ordering
App For Restaurant Students
Project Idea
Exception raised during
rendering: Unable to locate
mode 0
Android EventBus Library
Example
Day 3 of the 100 Days Android
App Development Challenge
for Beginners
Day 2 of 100 Days Android
App Development Challenge
for Beginners
Day 1 of 100 Days Android
App Development Challenge
for Beginners
Welcome to 100 Days Android
App Development Challenge
for Beginners
Android Record and Upload
Video to Server Using Retrofit
2
How to Program with your
Android Phone Using Aide IDE
Environment
Android Upload Image to
Server using Retrofit 2

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

2/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

Contactmeforcodeservices

CREATE NEW ANDROID PROJECT


Lets start to soil our hands in code. Start up your IDE. For this
tutorial, I am using the following tools and environment, feel free to
use what works for you.
Windows 10
Android Studio
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

3/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

Sony Xperia ZL
Min SDK 14
Target SDK 23
To create a new android application project, follow the steps as
stipulated below.
Go to File menu
Click on New menu
Click on Android Application
Enter Project name: AndroidRealtimeLocationTracking
Package: com.inducesmile.androidrealtimelocationtracking
Select Map Activity
Name your activity: MapsActivity
Keep other default selections
Continue to click on next button until Finish button is active, then
click on Finish Button.
Since
we selected the default android Map Activity template, Android
Contactmeforcodeservices

Studio will add an xml file name google_maps_api.xml. This file is


stored in the values folder inside the res folder of your android
project.
When you open the file, it contains instruction on how to obtain a
Google Map Key. Every request your application send to Google Map
Server requires a unique key that will be used to identify your
application.
Also, there is a limit to the number of request you can send in a day
if your are using the free service. Your Google map key also helps
Google to keep track of the number of request coming from your
app.
Copy for creating a Google Map Key and paste it in a web browser
and hit enter. You will see a page like this.

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

4/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

You can create a new project or use an existing project. Click the
continue button to proceed.
Click the Create AOI Key button that will appear in the next page to
move over to Google API Manager page.
In the Google API Manager page, click on credentials and the key link
to open the page.

Contactmeforcodeservices

Add a name for your key.


Select Android apps to restrict all the request from android apps
Add the your application package name
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

5/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

You can generate a SHA-1 certificate fingerprint. You will find the
process on the page.
Click the Save button when you are done.
Finally, copy your application Google map key to the generated

google_maps_api.xml as shown.

1.

<resources>

2.

<!-TODO: Before you run your application, you need


a Google Maps API key.

3.
4.

To get one, follow this link, follow the


directions and press "Create" at the end:

5.

https://console.developers.google.com/flows/enablea
pi?
apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDR
OID&r=57:A8:DD:42:FF:9E:71:B7:0D:2C:%3Bcom.inducesm
ile.androidmapdrawroute
6.

You can also add your credentials to an


existing key, using this line:

7.

57:A8:DD:42:FF:9E:88:E6:EC:69::46;com.inducesmile.a
ndroidmapdrawroute
8.

Alternatively, follow the directions here:

9.

https://developers.google.com/maps/documentation/an
droid/start#get-key
10.

Once you have your key (it starts with "AIza"),


replace the "google_maps_key"

Contactmeforcodeservices
11.
string in this file.
12.

-->

13.

<string name="google_maps_key"
templateMergeStrategy="preserve"
translatable="false">YOUR GOOGLE MAP API KEY
HERE</string>

14.

</resources>

BUILD.GRADLE
In android, since we are going to make use of user location in
drawing path between two points in Google Map API, we are going to
use Google Play Services. Android Location Service API is part of
Google Play Services.
Since the library is too big and to avoid going beyond 64000 methods
which will force use to multiDexEnabled true in the defaultConfig, we
will use Location and Map libraries alone.
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

6/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

Inaddition to these libraries, we are going to make use of Volley


network library and Gson library.
Open your application build.gradle and add the code below.
1.

apply plugin: 'com.android.application'

2.

android {

3.

compileSdkVersion 24

4.

buildToolsVersion "24.0.1"

5.

defaultConfig {

6.

applicationId
"com.inducesmile.androidlocationtracking"

7.

minSdkVersion 14

8.

targetSdkVersion 24

9.

versionCode 1
versionName "1.0"

10.
11.

12.

buildTypes {
release {

13.

minifyEnabled false

14.
15.

proguardFiles
getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}

16.

17.
18.

19.

dependencies {
compile fileTree(dir: 'libs', include:
['*.jar'])

20.

testCompile 'junit:junit:4.12'

21.
22.
23.

compile 'com.android.support:appcompatv7:24.2.1'
compile 'com.google.android.gms:play-servicesmaps:9.4.0'

Contactmeforcodeservices
24.
compile 'com.google.android.gms:play-serviceslocation:9.4.0'
25.

compile
'com.readystatesoftware.sqliteasset:sqliteassethelp
er:+'

26.

compile 'com.google.code.gson:gson:2.6.1'

27.

compile 'com.mcxiaoke.volley:library:1.0.19'

28.

ANDROIDMANIFEST.XML
We are going to update our application androidmanifest.xml. Using
Android Location requires that our application must request for user
permission before it can access their location. Starting from android
6, location request are run time permission which the user will grant
or deny while using the app.
Open your AndroidManifest.xml file and add the code below.
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

7/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

1.

<?xml version="1.0" encoding="utf-8"?>

2.

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid"

3.

package="com.inducesmile.androidlocationtracking">
4.

5.

6.

<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATI
ON" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCA
TION" />
<uses-permission
android:name="android.permission.INTERNET" />
<application
android:name=".network.CustomApplication"

7.
8.

android:allowBackup="true"

9.
10.

android:icon="@mipmap/ic_launcher"

11.

android:label="@string/app_name"

12.
13.

android:supportsRtl="true"
android:theme="@style/AppTheme">

14.

<activity android:name=".MainActivity">
<intent-filter>

15.
16.
17.

<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

18.

</activity>

19.
20.

<meta-data

21.
22.

android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key"

23.

/>
24.
<activity
Contactmeforcodeservices

android:name=".MapTrackingActivity"

25.
26.

android:label="@string/title_activity_map_tracking"
></activity>
27.
28.

<activity android:name=".SettingsActivity">
</activity>
<service

29.

android:name=".RouteService"

30.

android:enabled="true"

31.

android:exported="false"></service>

32.
33.
34.

<activity
android:name=".RecordResultActivity"></activity>
</application>
</manifest>

The meta-data retrieves the Google Map Key that we obtained


before.

STRINGS.XML
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

8/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

We are going to update our project strings.xml file located in the


values folder inside the res folder. Open the file and add the code
below to it.
1.

<resources>

2.

<string name="app_name">Android Real-time


Location Tracking</string>

3.

<string name="title_activity_map_tracking">Map
Route Tracking</string>

4.

<string name="track_path_on_map">Walk and route


your path on map</string>

5.

<string name="permission_notice">Please note


that your location permission is important if you
want to draw your route on map while walking or
running</string>

6.

<string name="permission_title">Location
Permission Denied</string>

7.

<string name="cancel_permission_notice">Wow,
please come back again when you need it and grant
the permission</string>

8.

</resources>

COLORS.XML
Open the colors.xml file in the same location as the strings.xml file
and add the code below to the file.
1.

<?xml version="1.0" encoding="utf-8"?>

2.

<resources>

3.

<color name="colorPrimary">#4CAF50</color>

5.

<color name="colorPrimaryLight">#C8E6C9</color>

6.

<color name="colorAccent">#4CAF50</color>

7.

<color name="colorPrimaryText">#212121</color>

Contactmeforcodeservices
4.
<color name="colorPrimaryDark">#388E3C</color>

8.
9.
10.
11.

<color
name="colorSecondaryText">#757575</color>
<color name="colorIcons">#FFFFFF</color>
<color name="colorDivider">#BDBDBD</color>
</resources>

ACTIVITY_MAP_TRACKING.XML
The MapTracking class main layout file consist of a Framelayout
ViewGroup with a Fragment and Button as children.
Open the layout file and add the code below.
1.

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/a

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

9/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

ndroid"
2.
3.

xmlns:map="http://schemas.android.com/apk/resauto"
xmlns:tools="http://schemas.android.com/tools"

4.

android:layout_height="match_parent"

5.

android:orientation="vertical"

6.

android:layout_width="match_parent">

7.

<fragment

8.

xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"

9.
10.

android:name="com.google.android.gms.maps.SupportMa
pFragment"
11.

android:layout_width="match_parent"

12.

android:layout_height="match_parent"

13.

android:layout_gravity="center"

14.

tools:context="com.inducesmile.androidlocationtrack
ing.MapTrackingActivity" />
<Button

15.
16.

android:id="@+id/start_tracking"

17.

android:layout_width="match_parent"

18.

android:layout_height="wrap_content"
android:padding="16dp"

19.
20.

android:background="@color/colorPrimaryDark"
21.

android:textColor="@color/colorIcons"

22.
23.

android:text="@string/start_tracking"
android:layout_gravity="bottom"

24.

android:layout_marginBottom="40dp"

25.

android:layout_marginRight="16dp"

26.

android:layout_marginLeft="16dp"
android:gravity="center"/>

27.
28.

</FrameLayout>

Contactmeforcodeservices

MAPTRACKINGACTIVITY CLASS
The MapTrackingActivity class will implement the
GoogleApiClient.ConnectionCallback interface. We will create an
instance of the GoogleApiClient which we will use to connect to
Google Play Services and interact with the Location Service API.
In the onConnection() callback method, we will create a location
request and check if the our device has the right location settings
before we can obtain the device current location. The
GoogleApiClient object is released in the onStop() callback method.
We have also created an inner RouteBroadCastReceiver class which
will receive intent from the background service to update the Map
route UI.

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

10/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

Open the MapTrackingActivity class and add the code below to it.
1.

import android.Manifest;

2.
3.

import android.content.BroadcastReceiver;
import android.content.Context;

4.

import android.content.Intent;

5.

import android.content.IntentFilter;

6.

import android.content.pm.PackageManager;

7.
8.

import android.graphics.Color;
import android.location.Location;

9.

import android.os.Bundle;

10.

import android.support.annotation.NonNull;

11.

import android.support.annotation.Nullable;

12.

import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;

13.
14.

import
android.support.v4.content.LocalBroadcastManager;

15.

import android.util.Log;

16.

import
com.google.android.gms.common.api.GoogleApiClient;
import
com.google.android.gms.common.api.PendingResult;

17.
18.

import
com.google.android.gms.common.api.ResultCallback;

19.

import com.google.android.gms.common.api.Status;
import
com.google.android.gms.location.LocationRequest;

20.
21.

import
com.google.android.gms.location.LocationServices;

import
com.google.android.gms.location.LocationSettingsReq
uest;
23.
import
com.google.android.gms.location.LocationSettingsRes
ult;
Contactmeforcodeservices

24.
import
com.google.android.gms.location.LocationSettingsSta
tusCodes;
22.

25.

import
com.google.android.gms.maps.CameraUpdateFactory;

26.

import com.google.android.gms.maps.GoogleMap;
import
com.google.android.gms.maps.OnMapReadyCallback;

27.
28.
29.
30.
31.
32.
33.
34.

35.
36.

import
com.google.android.gms.maps.SupportMapFragment;
import
com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import
com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import
com.google.android.gms.maps.model.PolylineOptions;
import
com.inducesmile.androidlocationtracking.database.Da
tabaseQuery;
import java.util.ArrayList;
import java.util.List;

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

11/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

37.

38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.

public class MapTrackingActivity extends


FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks{
private static final String TAG =
MapTrackingActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private double latitudeValue = 0.0;
private double longitudeValue = 0.0;
private GoogleMap mMap;
private DatabaseQuery mQuery;
private RouteBroadCastReceiver routeReceiver;
private List<LocationObject>
startToPresentLocations;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);

51.

setContentView(R.layout.activity_map_tracking);
52.
53.
54.

if (mGoogleApiClient == null) {
mGoogleApiClient = new
GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();

55.
56.
57.
58.
59.

}
mQuery = new DatabaseQuery(this);
startToPresentLocations =
mQuery.getAllLocationObjects();

mLocationRequest = createLocationRequest();
routeReceiver = new
RouteBroadCastReceiver();
62.
// Obtain the SupportMapFragment and get
notified when the map is ready to be used.
Contactmeforcodeservices
60.
61.

63.

SupportMapFragment mapFragment =
(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.m
ap);
mapFragment.getMapAsync(this);

64.
65.

66.

@Override
public void onMapReady(GoogleMap googleMap) {

67.
68.
69.
70.

71.

mMap = googleMap;
}
private void
markStartingLocationOnMap(GoogleMap mapObject,
LatLng location){
mapObject.addMarker(new
MarkerOptions().position(location).title("Current
location"));

72.

73.
74.
75.

mapObject.moveCamera(CameraUpdateFactory.newLatLng(
location));
}
@Override
public void onConnected(@Nullable Bundle
bundle) {

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

12/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

76.
77.

78.

79.
80.
81.
82.
83.
84.

Log.d(TAG, "Connection method has been


called");
LocationSettingsRequest.Builder builder =
new
LocationSettingsRequest.Builder().addLocationReques
t(mLocationRequest);
PendingResult<LocationSettingsResult>
result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient, builder.build());
result.setResultCallback(new
ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull
LocationSettingsResult result) {
final Status status =
result.getStatus();
switch (status.getStatusCode()) {
case
LocationSettingsStatusCodes.SUCCESS:

85.

if
(ActivityCompat.checkSelfPermission(getApplicationC
ontext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED

86.

&&
ActivityCompat.checkSelfPermission(getApplicationCo
ntext(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(m
GoogleApiClient);
if (mLastLocation !=
null) {

87.

88.

latitudeValue =

89.

mLastLocation.getLatitude();
90.

Contactmeforcodeservices

mLastLocation.getLongitude();
91.

92.

longitudeValue =

Log.d(TAG,
"Latitude 4: " + latitudeValue + " Longitude 4: " +
longitudeValue);
refreshMap(mMap);

93.

94.
95.

markStartingLocationOnMap(mMap, new
LatLng(latitudeValue, longitudeValue));
startPolyline(mMap,
new LatLng(latitudeValue, longitudeValue));
}
}
break;

96.
97.
98.

case
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAIL
ABLE:
break;

99.

100.

101.

});

102.
103.

104.
105.

@Override
public void onConnectionSuspended(int i) {

106.

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

13/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

107.
108.
109.
110.
111.

private class RouteBroadCastReceiver extends


BroadcastReceiver{
@Override
public void onReceive(Context context,
Intent intent) {
String local =
intent.getExtras().getString("RESULT_CODE");
assert local != null;
if(local.equals("LOCAL")){
//get all data from database

112.
113.
114.

startToPresentLocations =
mQuery.getAllLocationObjects();
if(startToPresentLocations.size() >

115.

0){
//prepare map drawing.

116.
117.
118.
119.

List<LatLng> locationPoints =
getPoints(startToPresentLocations);
refreshMap(mMap);
markStartingLocationOnMap(mMap,
locationPoints.get(0));
drawRouteOnMap(mMap,

120.

locationPoints);
}

121.

122.

123.

124.
125.

private List<LatLng>
getPoints(List<LocationObject> mLocations){
List<LatLng> points = new ArrayList<LatLng>

126.

();
127.
128.

129.
130.

for(LocationObject mLocation : mLocations){


points.add(new
LatLng(mLocation.getLatitude(),
mLocation.getLongitude()));
}
return points;

Contactmeforcodeservices
}

131.
132.
133.
134.
135.
136.
137.

138.
139.
140.
141.
142.
143.

private void startPolyline(GoogleMap map,


LatLng location){
if(map == null){
Log.d(TAG, "Map object is not null");
return;
}
PolylineOptions options = new
PolylineOptions().width(5).color(Color.BLUE).geodes
ic(true);
options.add(location);
Polyline polyline =
map.addPolyline(options);
CameraPosition cameraPosition = new
CameraPosition.Builder()
.target(location)
.zoom(16)
.build();

144.

map.animateCamera(CameraUpdateFactory.newCameraPosi
tion(cameraPosition));
145.
146.

}
private void drawRouteOnMap(GoogleMap map,
List<LatLng> positions){

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

14/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

147.

148.

PolylineOptions options = new


PolylineOptions().width(5).color(Color.BLUE).geodes
ic(true);
options.addAll(positions);

149.

Polyline polyline =
map.addPolyline(options);

150.

CameraPosition cameraPosition = new


CameraPosition.Builder()
.target(new
LatLng(positions.get(0).latitude,
positions.get(0).longitude))
.zoom(17)

151.

152.
154.

.bearing(90)
.tilt(40)

155.

.build();

153.

156.

157.
158.
159.
160.
161.
162.

map.animateCamera(CameraUpdateFactory.newCameraPosi
tion(cameraPosition));
}
private void refreshMap(GoogleMap mapInstance){
mapInstance.clear();
}
protected LocationRequest
createLocationRequest() {
LocationRequest mLocationRequest = new
LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);

163.
164.
165.

mLocationRequest.setPriority(LocationRequest.PRIORI
TY_HIGH_ACCURACY);
return mLocationRequest;

166.
167.
168.
169.
170.

}
@Override
protected void onResume() {
super.onResume();

Contactmeforcodeservices
if(routeReceiver ==

171.
172.
173.
174.

null){
routeReceiver = new
RouteBroadCastReceiver();
}
IntentFilter filter = new
IntentFilter(RouteService.ACTION);

175.

176.
177.
178.

LocalBroadcastManager.getInstance(this).registerRec
eiver(routeReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();

179.
180.

181.
182.
183.
184.

LocalBroadcastManager.getInstance(this).unregisterR
eceiver(routeReceiver);
}
@Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();

185.
186.

187.

@Override
protected void onStop() {

188.

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

15/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

mGoogleApiClient.disconnect();
super.onStop();

189.
190.

191.
192.

ROUTESERVICE CLASS
The RouteService class is an android service class that runs in the
background. The service starts when a user toggle the start tracking
button and you can as well stop it with the button is the button uses
a flag to tracking the state of the service class.
The RouteService class implements the GoogleApiClient
OnConnectionCallbacks, OnConnectionFailedListener and
LocationListener.
The LocationListener overrides the onLocationChange() method
which pass the current location as parameter.
The location is stored in SQLite database and the Service class will
notify the Local Broadcast Receiver class of the location update.
Open the RouteService.java file and add the code below.
1.

import android.Manifest;

import android.app.Service;
3.
import android.content.Intent;
Contactmeforcodeservices

4.
import android.content.pm.PackageManager;
2.

5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import
android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import
com.google.android.gms.common.ConnectionResult;
import
com.google.android.gms.common.api.GoogleApiClient;

15.

import
com.google.android.gms.common.api.PendingResult;

16.

import
com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

17.
18.

import
com.google.android.gms.location.LocationListener;

19.

import
com.google.android.gms.location.LocationRequest;

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

16/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

20.
21.

22.

import
com.google.android.gms.location.LocationServices;
import
com.google.android.gms.location.LocationSettingsReq
uest;
import
com.google.android.gms.location.LocationSettingsRes
ult;

23.

import
com.google.android.gms.location.LocationSettingsSta
tusCodes;

24.

import
com.inducesmile.androidlocationtracking.database.Da
tabaseQuery;
import
com.inducesmile.androidlocationtracking.helpers.Cus
tomSharedPreference;
public class RouteService extends Service
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG =
RouteService.class.getSimpleName();

25.

26.

27.
28.

29.
30.
31.
32.
33.
34.
35.
36.
37.

public static final String ACTION =


"com.inducesmile.androidlocationtracking.RouteServi
ce";
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private double latitudeValue = 0.0;
private double longitudeValue = 0.0;
private CustomSharedPreference
customSharedPreference;
private DatabaseQuery query;
private long startTimeInMilliSeconds = 0L;
private boolean isServiceRunning = false;

38.
@Override
Contactmeforcodeservices

39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.

public void onCreate() {


super.onCreate();
customSharedPreference = new
CustomSharedPreference(getApplicationContext());
if(isRouteTrackingOn()){
startTimeInMilliSeconds =
System.currentTimeMillis();
Log.d(TAG, "Current time " +
startTimeInMilliSeconds);
Log.d(TAG, "Service is running");
}
query = new
DatabaseQuery(getApplicationContext());
mLocationRequest = createLocationRequest();
if (mGoogleApiClient == null) {
mGoogleApiClient = new
GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)

52.
53.
54.
55.

.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

17/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

56.
57.
58.
59.
60.

}
@Override
public int onStartCommand(Intent intent, int
flags, int startId) {
isServiceRunning = true;
return Service.START_STICKY;

61.
62.

63.

@Nullable
@Override
public IBinder onBind(Intent intent) {

64.
65.

return null;

66.
67.
68.
69.
70.

}
@Override
public void onConnected(@Nullable Bundle
bundle) {
Log.d(TAG, "Connection method has been
called");

71.

LocationSettingsRequest.Builder builder =
new
LocationSettingsRequest.Builder().addLocationReques
t(mLocationRequest);

72.

PendingResult<LocationSettingsResult>
result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient, builder.build());

73.

result.setResultCallback(new
ResultCallback<LocationSettingsResult>() {
@Override

74.
75.
76.
77.

public void onResult(@NonNull


LocationSettingsResult result) {
final Status status =
result.getStatus();
switch (status.getStatusCode()) {

case
LocationSettingsStatusCodes.SUCCESS:
Contactmeforcodeservices
79.
if
(ActivityCompat.checkSelfPermission(getApplicationC
ontext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
80.
&&
ActivityCompat.checkSelfPermission(getApplicationCo
ntext(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
81.
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(m
GoogleApiClient);
82.
if (mLastLocation !=
null) {
78.

latitudeValue =

83.

mLastLocation.getLatitude();
longitudeValue =

84.

mLastLocation.getLongitude();
85.

Log.d(TAG,
"Latitude 1: " + latitudeValue + " Longitude 1: " +
longitudeValue);

86.

LocationServices.FusedLocationApi.requestLocationUp
dates(mGoogleApiClient, mLocationRequest,
RouteService.this);
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

18/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

87.

88.
89.
90.

91.

break;
case
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAIL
ABLE:
break;
}

92.

93.
94.
95.
96.
97.
98.
99.
100.
101.

});
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull
ConnectionResult connectionResult) {
}

102.

protected LocationRequest
createLocationRequest() {

103.

LocationRequest mLocationRequest = new


LocationRequest();
mLocationRequest.setInterval(5000);

104.
105.

mLocationRequest.setFastestInterval(3000);

106.

107.
108.
109.
110.

mLocationRequest.setPriority(LocationRequest.PRIORI
TY_HIGH_ACCURACY);
return mLocationRequest;
}
@Override
public void onLocationChanged(Location
location) {

Log.d(TAG, "Latitude " +


location.getLatitude() + " Longitude " +
location.getLongitude());
112.
Log.d(TAG, "SERVICE RUNNING " +
Contactmeforcodeservices

isServiceRunning);
113.
if(isRouteTrackingOn() &&
startTimeInMilliSeconds == 0){
111.

114.
115.
116.
117.
118.
119.

startTimeInMilliSeconds =
System.currentTimeMillis();
}
if(isRouteTrackingOn() &&
startTimeInMilliSeconds > 0){
latitudeValue = location.getLatitude();
longitudeValue =
location.getLongitude();
Log.d(TAG, "Latitude " + latitudeValue
+ " Longitude " + longitudeValue);
// insert values to local sqlite

120.

database
121.

122.
123.

query.addNewLocationObject(System.currentTimeMillis
(), latitudeValue, longitudeValue);
// send local broadcast receiver to
application components
Intent localBroadcastIntent = new
Intent(ACTION);

124.

localBroadcastIntent.putExtra("RESULT_CODE",
https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

19/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

"LOCAL");
125.

LocalBroadcastManager.getInstance(getApplicationCon
text()).sendBroadcast(localBroadcastIntent);
long timeoutTracking = 2 * 60 * 60 *

126.

1000;
127.
128.

if(System.currentTimeMillis() >=
startTimeInMilliSeconds + timeoutTracking){
//turn of the tracking

129.
130.
131.

customSharedPreference.setServiceState(false);
Log.d(TAG, "SERVICE HAS BEEN
STOPPED");
this.stopSelf();
}
}
if(!isRouteTrackingOn()){

132.
133.
134.

Log.d(TAG, "SERVICE HAS BEEN STOPPED

135.

1");
isServiceRunning = false;

136.
137.

Log.d(TAG, "SERVICE STOPPED " +


isServiceRunning);

138.

Intent dialogIntent = new Intent(this,


RecordResultActivity.class);

139.

140.

dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
);
this.startActivity(dialogIntent);
this.stopSelf();

141.

142.
143.
144.
145.

}
private boolean isRouteTrackingOn(){
Log.d(TAG, "SERVICE STATE " +
customSharedPreference.getServiceState());

return
customSharedPreference.getServiceState();
Contactmeforcodeservices

147.
}
146.

@Override
public void onDestroy() {
mGoogleApiClient.disconnect();

148.
149.
150.

super.onDestroy();

151.

152.
153.

This brings us to the end of this tutorial. I hope that you have learn
something. Run your app and take a work around you will see how
your location is being drawn on the map.
You can download the code for this tutorial below. If you are having
hard time downloading the tutorial, kindly contact me.
Remember to subscribe with your email address to be among the
first to receive my new android blog post once it is published.

OTHER INTERESTING POSTS:


https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

20/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

Android HTML Parser Using


JSOUP Tutorial

How to Create Android


Splash Screen

Android ToolBar With Tab


and Horizontal Swipe View

Download Remote Audio


File in Android Application

Contactmeforcodeservices
API
Android
Json Parsing using
Android Camera2
Gson and RecyclerView
Example Tutorial

Tags: Android Real-time User Location Tracking Using Google Map


API v2, location tracking in android, location tracking with Google
Map

ABOUT THE AUTHOR


Henry
I like Java. I breath Android and iOS. I love Yii
and Javascript

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

21/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

6 COMMENTS

roger

October 27, 2016

Log in to Reply

Hi Henry,
This is very useful tutorial. I just wonder if you can
also post class source code of LocationObject as
well as the database source code so that to make
it as a complete example that I can learn and try.
Thanks a lot
Ling
View Comment

Henry Author

October 27, 2016

Log in to Reply

Thanks, I will do that when time permits me. Kindly


keep checking back
View Comment

Contactmeforcodeservices
akhil

October 27, 2016

Log in to Reply

how would i save the data travelled in sqlite and


use it when i click button reroute ???
View Comment

Henry Author

October 27, 2016

Log in to Reply

I will soon provide more information with regards to


saving real-time location data in SQLite database.
View Comment

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

22/23

9/12/2016

AndroidRealtimeUserLocationTrackingUsingGoogleMapAPIv2

roger

October 29, 2016

Log in to Reply
Thanks a lot! Look forward to see the SQLite
database for location data
View Comment

roger

October 29, 2016

Log in to Reply

By the way , what does RecordResultActivity.class


do in this app?
Is it a new activity class that record the data? How
is it different fromMapTrackingActivity?
View Comment

ADD A COMMENT
You must be logged in to post a comment.

INDUCESMILE ANDROID TUTORIAL, ANDROID APPS, ANDROID STUDIO, ANDROID SDK, ANDROID

Contactmeforcodeservices

DEVELOPMENT COPYRIGHT 2016.

ANDROID STUDENT ASSIGNMENT HELP


ASK QUESTIONS

ANDROID TUTORIALS

BUY APPS FROM $1

CONTACT US

https://inducesmile.com/android/androidrealtimeuserlocationtrackingusinggooglemapapiv2/

23/23

You might also like