DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Location Aware App in Android: UV Index

Location Aware App in Android: UV Index

Learn how to leverage Google Play services to make your app location aware with this useful tutorial.

Francesco Azzola user avatar by
Francesco Azzola
CORE ·
Apr. 15, 16 · Tutorial
Like (3)
Save
Tweet
Share
4.81K Views

Join the DZone community and get the full member experience.

Join For Free

as you may already know google play services is a set of services that extend android app features by providing a new set of services like google map , google plus , location service and more. this post focuses on using google play location services to make a location aware app . to show how to make it and how to set up an android app based on google play services , we will develop an app that shows the current uv index using your location. to get the uv index the app will use the openweathermap api .

the final result is shown below:
android location aware app

the first thing is setting up the google play location service in build.gradle :

dependencies {
..
 compile 'com.google.android.gms:play-services:8.4.0'
..
}


now the library is ready and we can use it in developing our android app. the android uv index app should be aware of the current location so that it can pass the latitude and longitude to the openweathermap api to get the current uv index. we have to develop a google play services client to invoke the services exposed by google play so that the app can retrieve the current location.

making the client is very simple and we need just a few lines of code:

private void initgoogleclient() {
 googleclient = new googleapiclient.builder(this)
 .addconnectioncallbacks(this)
 .addonconnectionfailedlistener(this)
 .addapi(locationservices.api)
 .build();
}


on line 5, we specify we use locationservices.api . the initgoogleclient is called in oncreate method so that we initialise the google play location services client as soon as the app starts.


it is important to remember to disconnect the client to the services when the app stops:

@override
protected void onstop() {
 googleclient.disconnect();
 super.onstop();
}


and to reconnect the client when the app starts:

@override
protected void onstart() {
 googleclient.connect();
 super.onstart();
}


there's just one more thing before the google play services is ready. it is necessary to register the app to listen when the connection fails or the connection is ready:

// connection failure
 @override
 public void onconnectionfailed(@nonnull connectionresult connectionresult) {
 showerrormessage();
 return;
 }

 // connection established
 @override
 public void onconnected(@nullable bundle bundle) {
 getuvindex();
 }


the google play services client is ready and  when the connection is ready the app retrieves the uv index.

the next step is making adding  location awareness, so that the app can retrieve current uv index.
before implementing the app, it is necessary to grant the permission in the manifest.xml :

<uses-permission android:name="android.permission.access_coarse_location"/>


to make the app location aware , we can ask the last known location using:

private location getlocation() {
 try {
 location loc = locationservices.fusedlocationapi.getlastlocation(googleclient);
 return loc;
 }
 catch(securityexception se) {}
 return null;
}


where googleclient is the client we talked about in the previous paragraph.
this method can return null value so the app can register itself for location updates so that it gets informed when the location changes:

locationrequest req = new locationrequest();
req.setinterval(60 * 60 * 1000);
req.setpriority(locationrequest.priority_balanced_power_accuracy);
locationservices.fusedlocationapi.requestlocationupdates(googleclient, req, this);


where the interval is the notification interval. to know more about locationrequest refer to the official documentation.

to get the uv index from openweathermap, it is necessary to send the current location expressed as latitude and longitude:

http://api.openweathermap.org/v3/uvi/{lat},{lon}/current.json?appid={your-api-key}

and of course, the api-key. you can get it creating an account. if you want to have more information go to how to invoke openweathermap api in android . to invoke the openweathermap api is very simple once we known the current location ( latitude and longitude ).
the android app location aware has to make an http call to the openweathermap api and parse the json response.

as http client library, the app uses okhttp library, so the build.gradle is:

dependencies {
 ..
 compile 'com.android.support:appcompat-v7:23.2.1'
 compile 'com.android.support:design:23.2.1'
 compile 'com.google.android.gms:play-services:8.4.0'
 compile 'com.squareup.okhttp3:okhttp:3.2.0'
}


once the dependency is configured to make an http request is very simple:

private void handleconnection(location loc) {

 double lat = loc.getlatitude();
 double lon = loc.getlongitude();

 // make http request according to openweathermap api
 string url = uv_url + ((int) lat) + "," + ( (int) lon) + "/current.json?appid=" + app_id;
 system.out.println("url ["+url+"]");
 request request = new request.builder()
 .url(url)
 .build();
 httpclient.newcall(request).enqueue(new callback() {
 @override
 public void onfailure(call call, ioexception e) {
 // handle failure in http request
 }

 @override
 public void onresponse(call call, response response) throws ioexception {
 // ok we have the response...parse it
 try {
 jsonobject obj = new jsonobject(response.body().string());
 final double uvindex = obj.optdouble("data");
 system.out.println("uv index ["+uvindex+"]");
 jsonobject jsonloc = obj.getjsonobject("location");
 final double clon = jsonloc.getdouble("longitude");
 final double clat = jsonloc.getdouble("latitude");

 handler handler = new handler(mainactivity.this.getmainlooper());
 handler.post(new runnable() {
 @override
 public void run() {
 // handle ui update
 }
 });
 }
 catch(jsonexception jex) {
 jex.printstacktrace();
 }
 }
 });
 }

the final result is shown in the picture below:
android location aware app

the color of the value shown in the image above changes according to uv index scale .

to test the app, it is necessary to use a simple android app that returns fake gps location and enables fake gps position in your smartphone under the developer section in the configuration menu.

source code available soon.

app Android (robot) Google Play Services Google (verb)

Published at DZone with permission of Francesco Azzola, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Differences Between Site Reliability Engineer vs. Software Engineer vs. Cloud Engineer vs. DevOps Engineer
  • Implementing Infinite Scroll in jOOQ
  • Visual Network Mapping Your K8s Clusters To Assess Performance
  • Do Not Forget About Testing!

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: