Professional Documents
Culture Documents
AGPSLocationPlottingAndroidApplicationCodeProject
articles
Q&A
Sign in
forums
lounge
CPOL
Rate this:
4.59 36 votes
Introduction
Recently, I was tasked with writing an application that heavily relied on GPS and mapping of custom hardware
devices that were built with locationaware components. Even though I have been using Eclipse for these tasks
for quite some time, Android Studio's glittering new features and ease of use caught my attention to try it out
for the task. During the few weeks I had worked with Android Studio and with Google Maps Android API V2, I
learned some lessons that are worth sharing, so that others need not reinvent the wheel and avoid the known
pitfalls on their quest.
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
1/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
In this article, we will try to focus on developing an Android application that uses Google Maps Android API
V2, using Android Studio IDE. Very recently Google deprecated and as of March 18th, 2013, stopped issuing
API keys for Google Maps Android V1 and started recommending V2. A lot of documentation, books and
other resources on the web discuss doing things that are centered around V1 and it is daunting for a new
comer to sieve through all that and get some useful information on developing applications using API V2. To
add to the confusion, there is not very many resources on the web that discusses using Android Studio for
such development. Let us hope to fill that gap here.
Background
Google announced on May 16th, 2013, at their Google I/O conference, Android Studio as their Integrated
Development Environment, IDE, of choice to develop Android Applications. Android Studio is essentially
InettliJ IDEA from JetBrains, but is heavily focused on the development of Android applications. Android Studio
uses Gradle for dependency resolution and most of the project management tasks in the IDE. Android Studio
is available for download from here.. Android Studio has an automatic software updater that automatically
checks for new updates and updates the IDE to the latest version. As of this writing, the newest version was
0.2.11, Build AI132.855830.
Prior to Android Studio and even after, majority of developers use Eclipse as a fundamental platform for
Android application development. Eclipse is an excellent platform that provides a great IDE for software
development in Java, C++ and various other languages.
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
2/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
OffersWizardAds
OffersWizardAds
adbyOffersWizard
x
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
3/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
Even though there are many files created in this process, luckily, we are going to focus on only the following
five files:
MainActivity.java
activity_main.xml
strings.xml
AndroidManifest.xml
build.gradle
Location Providers
Before we start to modify these files, let us discuss some background on why we do what we do in the
following sections. Android devices are equipped with GPS hardware. Android provides a very straight forward
API to access Location information derived from GPS hardware along with WiFi and Cellular network
connection sources that helps provide location information. Since an application should be able to access the
current location information of the device, we need to get the users permission for the application to access
this service during installation. During debugging, the application is given permission to access these services,
without prompting the user to acknowledge. The following section sets up various permissions for the
application to access such as accessing internet, since Maps are to be downloaded from Internet, accessing
Storage, since Maps need to be cached and for accessing Location providers such as GPS and other forms of
location services. Android Maps also needs OpenGL. Here are the lines added to our AndroidManifest.xml file
just above the <aplication> tag.
Hide Copy Code
<usespermissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
<usespermissionandroid:name="android.permission.INTERNET"/>
<usespermissionandroid:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!Externalstorageforcaching.>
<usespermissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!MyLocation>
<usespermissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
<usespermissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>
<!MapsAPIneedsOpenGLES2.0.>
<usesfeature
android:glEsVersion="0x00020000"
android:required="true"/>
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
4/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
Once Google Play Services API is installed, we need to include it in our project. The very nice tutorial at
Google's android developer site is written targeting Eclipse as the platform, it suggests including a reference
to the Google Services Library by Importing it into the workspace. This will not work with Android Studio since
Gradle is used for dependency resolution here. So, we need to edit build.gradle file as follows, by adding a
single line in the dependency section of it. Please note, as of this writing, the UI can not be used to add this
dependency for Gradle. The only way is to edit the build.gradle file manually. However, one must realize that
this is much simpler than the solution discussed at the developer's site.
Hide Copy Code
dependencies{
//GooglePlayServices
compile'com.google.android.gms:playservices:3.2.65'
//SupportLibrary
compile'com.android.support:appcompatv7:18.0.0'
}
Now, to show a map in our application, we need a Fragment in our layout. This is done by replacing the
TextView section in the activity_main.xml file with a Fragment section as follows:
Hide Copy Code
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
5/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
And modifying MainActivity.java by deriving the MainActivity class from FragmentActivity instead of
Activity, as follows:
Hide Copy Code
publicclassMainActivityextendsFragmentActivity
Now, technically we have everything on the device side of the application. However, the Map has to come
from the Cloud. To access the Maps from the cloud, we need a special authentication key called API Key, given
to our application by the Google Cloud services, where the Maps are served from. Even though it sounds very
complicated, it is very straight forward to obtain this key by following the instructions given here
Please note that for our purposes, we can use our debug certificate to obtain our API Key. A release certificate
should be used for generating this key, only if we are going to publish the application. Once this key is
obtained, copy this key into the AndroidManifest.xml file as follows, just above <xmp></xmp> tag.
Hide Copy Code
<metadata
android:name="com.google.android.maps.v2.API_KEY"
android:value="YourAPIKeyHere!!"/>
Please note, it is much simpler to connect an Android device to the PC and install this application on it and
test it than to use the Emulator. However, please remember to enable USB debugging on the device. If your
device is running Jelly Bean, by default, Developer Options section of the Settings menu is hidden to protect
the user from doing any harm with this feature. Go to System Settings Menu and scroll all the way down to see
if you see Developer Options listed. If it is not listed, to bring the Developer Options to view, select About
Phone menu and scroll all the way down where you see Build Number. Keep tapping on Build Number several
times rapidly until you see that Developer Options are enabled. Go into Developer Options menu and enable
USB debugging by clicking on the check mark against it.
Connect your device to the PC with the USB cable and hit run on the Android Studio Menu. If everything went
well, you would see a Google map displayed centered somewhere around the continent of Africa! That's not
much work, is it.
6/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
We can obtain the map object reference by getting the reference to the Fragment that we inserted in the
layout file as follows:
Hide Copy Code
myMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
Now, to mark our location on the map, with a blue arrow icon, we enable the feature in our map object as
follows. Note, we check for null since the map may not be available before it is rendered completely.
Hide Copy Code
if(myMap!=null)
{
myMap.setMyLocationEnabled(true);
}
Since we now have the object reference for the map, we can now start to listen to the location updates from
location services. The recommended method for doing this is to setup a location client for the location
services within our Main Activity with the following code
Hide Copy Code
myLocationClient=newLocationClient(getApplicationContext(),this,this);
//oncewehavethereferencetotheclient,connectit
if(myLocationClient!=null)
myLocationClient.connect();
The LocationClient object constructor takes three parameters, the first is the application context and the
second is the object that implements Connection callbacks, such as establishment of connection and
Disconnection, and the third is the object that implements Connection failure listener. Since we pass the
reference to the MainActivity object as the two call back inputs, we have to implement those methods in
our MainActivity class. Once we modify our MainActivity class definition line as follows to implement
those two interfaces and the LocationListener interface. Android Studio will prompt us to implement the
required methods and will automatically populate our class with the methods.
Hide Copy Code
publicclassShowMeOnMapextendsFragmentActivity
implementsGooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener{
The following are the methods that are populated by Android Studio to implement those three interfaces:
Hide Copy Code
@Override
publicvoidonConnected(Bundlebundle){
}
@Override
publicvoidonDisconnected(){
}
@Override
publicvoidonLocationChanged(Locationlocation){
}
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
7/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
@Override
publicvoidonConnectionFailed(ConnectionResultconnectionResult){
}
As the names suggests, OnConnected is fired when the the service is connected to our LocationClient
object. Here is where we have to register our LocationListener to listen for location updates. So, we edit
this method body as follows
Hide Copy Code
@Override
publicvoidonConnected(Bundlebundle){
myLocationClient.requestLocationUpdates(REQUEST,this);
}
As you already know, the this in the requestLocationUpdates call is the reference to our MainActivity
since we are implementing the LocationListener Interface here. The first parameter is the
LocationRequest object that sets options for the location updates such as update frequency, accuracy etc.
This is defined as follows:
Hide Copy Code
privatestaticfinalLocationRequestREQUEST=LocationRequest.create()
.setInterval(5000)//5seconds
.setFastestInterval(16)//16ms=60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
myMap.moveCamera(CameraUpdateFactory.newCameraPosition(
newCameraPosition.Builder().target(newLatLng(lat,lng))
.zoom(15.5f)
.bearing(0)
.tilt(25)
.build()
),newGoogleMap.CancelableCallback(){
@Override
publicvoidonFinish(){
//YourcodeheretodosomethingaftertheMapisrendered
}
@Override
publicvoidonCancel(){
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
8/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
//YourcodeheretodosomethingaftertheMaprenderingiscancelled
}
});
In essence, what we have done so far should result in an application that loads a map and shows our position
on it with a blue arrow. This icon will track our location on the map as we move around. However, we have
neglected some of the details, for the sake of simplicity here. For instance, we have neglected the life cycle
events of the MainActivity where is could be Paused and Resumed etc. In the event of another activity
displayed over our MainActivity,preventing it from displaying, our MainActivity will be Paused and
sent to the background and an onPause()event is generated. When the user gets back to our activity, it will
be Resumed and an onResume() event is generated. Location updates are expensive in terms of battery life.
So, as a responsible citizen of the Android application habitat, our application should disable location updates
when sent to background and not displayed and enable back again when resumed. This is done by overriding
onPause() and onResume() methods of the MainActivity. Please refer to the complete application in the
source code bundle.
To use the source code and create an application for your own, please follow these steps:
1. Unzip the source in a folder
2. Since Creating API key needs an application name, follow what we said in this article, starting with
creating new project in Android Studio, with your preferred application name.
3. Then copy the contents of MainActivity.java from the source you unzipped and paste it in your new
MainActivity.java completely replacing the contents. Then go over to the very first line in the file and
change the line "package com.siriusmicrotech.gpsplotter with your package name that you used during
your new project creation.
4. Copy the contents of activity_main.xml file from the source you unzipped and paste it in your new
activity_main.xml file replacing the contents entirely.
5. Copy and paste contents of build.gradle file from unzipped source on to your new buld.gradle file
replacing contents entirely.
6. Do the same for AndroidManifest.xml file. However, here, you have to change the third line from top to
replace com.siriusmicrotech.gpsplotter with your package name and under the <activity>
tag, change android:name="com.siriusmicrotech.gpsplotter.MainActivity" with your
activity name.
7. Get your API key from Google Could Services
8. Copy and paste your API key in the AndroidManifest.xml file to replace string that reads "Your API Key
Here!"
9. That's it.
Points of Interest
Things to pay attention to Get the latest version of Android Studio build. If you decided to use Android
Studio, do not research on the internet for solutions, since almost all the text is written for Eclipse. There is a
significant change in the way things are done in Google Maps Android API V2 than it was done in V1. Most of
the text in elsewhere in internet are written with reference to V1 and that would cripple your progress real bad.
The solution is to head over to Google Developer site for API V2 and you will be much better off.
License
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
9/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
This article, along with any associated source code and files, is licensed under The Code Project Open License
CPOL
Share
EMAIL
Raja.D.Singh is one of the Founders of Sirius Microtech LLC, a Los Angeles based technology company
dedicated to provide Innovative Engineering services and excellent, standards compliant solutions for
problems faced by Small to Medium sized engineering organizations. Sirius specializes in New Product
development for Industrial Automation, Robotics, Alternative Energy and Real Time Embedded Systems.
Follow on
Go
First Prev Next
GPS
Member 11587922
7Apr15 7:06
10/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
Member 11072073
6Jan15 23:31
1 2 3 Next
News
Suggestion
Question
Bug
Answer
Joke
Rant
Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150516.1 | Last Updated 9 Oct 2013
Select Language
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
11/12
5/20/2015
AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
12/12