Android Location API Using Google Play Services

16
Android Location API using Google Play Services Android GPS, Location Manager , I explained how to get device location (latitude & longitude) using the older android APIs. Now google introduced new Services. A newer api called FusedLocationApi was introduced which connects with GoogleApiClient and gives us the best location available. So let’s start this by creating a simple app. 1. Downloading & Importing Google Play Services As this app needs Google Play Services, we need to setup the play services first. If you have the play services installed already, update them to latest version 1. Open Android SDK Manager and install or update the play services under Extras section. 2. In Eclipse goto File Import Android Existing Android Code Into Workspace 3. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib 4. And check Copy projects into workspace option as shown in the below image, which places a copy of play services in eclipse workspace.

description

Android Location API using Google Play Services...Android Location API using Google Play Services.pdf

Transcript of Android Location API Using Google Play Services

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 1/16

    Android Location API using Google Play ServicesAndroid GPS, Location Manager, I explained how to get device location (latitude & longitude) using the older android APIs. Now google introduced new way of getting device location using the Google PlayServices.

    A newer api called FusedLocationApi was introduced which connects with GoogleApiClient and gives us the best location available.

    So lets start this by creating a simple app.

    1. Downloading & Importing Google Play Services

    As this app needs Google Play Services, we need to setup the play services first. If you have the play services installed already, update them to latest version using Android SDK Manager.

    1. Open Android SDK Manager and install or update the play services under Extras section.

    2. In Eclipse goto File Import Android Existing Android Code Into Workspace

    3. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project fromandroid-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib

    4. And check Copy projects into workspace option as shown in the below image, which places a copy of play services in eclipse workspace.

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 2/16

    2. Creating Android Project

    Once the play services are downloaded and imported into eclipse workspace, we can start building a simple app with the location services integrated.

    1. In Eclipse create a new android project by navigating to File New Android Application Project and fill out all the required details.

    I gave my project name as Location API and package name as info.androidhive.locationapi

    2. Add the Google Play Services project as a library to our project. Right click on the project and select properties. In the properties window, on left side select under library section. Click it and select google play services library which we imported previously

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 3/16

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 4/16

    3. Download this marker.png and paste it in your projects src res drawable-ldpi folder. (Please note that this is a white color png image, it might not be visible in your browser window)

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 5/16

    4. Open strings.xml located under res values and add below string values.

    5. Open colors.xml located under res values and add below color values. If you dont see colors.xml, create a new file with the name.

    6. Open AndroidManifest.xml and add ACCESS_FINE_LOCATION permission. You also need to add below meta-data for google play services version.

    After doing required changes, your AndroidManifest.xml should look like below.

    strings.xml

    LocationAPIYOUAREATGETMYLOCATIONSTARTLOCATIONUPDATESSTOPLOCATIONUPDATES

    colors.xml

    #b20e0f#ffffff#3e4a56

    AndroidManifest.xml

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 6/16

    7. Now well quickly create a simple layout for our app. Open the layout file of your main activity (activity_main.xml) and add below code. This layout contains a TextView to display the location and two buttons(one is to get location and other is to toggle periodic location updates).

    8. Now well start adding the code related to location api. Open your main activity MainActivity.java and implement the class from ConnectionCallbacks, OnConnectionFailedListener

    In brief, you need to do below changes in your activity to get the users current location.

    > First check for availability of Google Play Services by calling checkPlayServices() in onResume()

    > Once play services are available on the device, build the GoogleApiClient by calling buildGoogleApiClient() method.

    activity_main.xml

    publicclassMainActivity1extendsActivityimplementsConnectionCallbacks,OnConnectionFailedListener{}

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 7/16

    > Connect to google api client by calling mGoogleApiClient.connect() in onStart() method. By calling this, onConnectionFailed(), onConnected() and onConnectionSuspended()upon the connection status.

    > Once google api is successfully connected, displayLocation() should be called in onConnected() method to get the current location.

    Add the below code to your main activity and run the project. Make sure that the wifi and location is enabled on your device before you test.

    MainActivity.javapackageinfo.androidhive.locationapi;importcom.google.android.gms.common.ConnectionResult;importcom.google.android.gms.common.GooglePlayServicesUtil;importcom.google.android.gms.common.api.GoogleApiClient;importcom.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;importcom.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;importcom.google.android.gms.location.LocationRequest;importcom.google.android.gms.location.LocationServices;importandroid.app.Activity;importandroid.location.Location;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.View;importandroid.widget.Button;importandroid.widget.TextView;importandroid.widget.Toast;publicclassMainActivity1extendsActivityimplementsConnectionCallbacks,OnConnectionFailedListener{//LogCattagprivatestaticfinalStringTAG=MainActivity.class.getSimpleName();privatefinalstaticintPLAY_SERVICES_RESOLUTION_REQUEST=1000;privateLocationmLastLocation;//GoogleclienttointeractwithGoogleAPIprivateGoogleApiClientmGoogleApiClient;//booleanflagtotoggleperiodiclocationupdatesprivatebooleanmRequestingLocationUpdates=false;privateLocationRequestmLocationRequest;//LocationupdatesintervalsinsecprivatestaticintUPDATE_INTERVAL=10000;//10secprivatestaticintFATEST_INTERVAL=5000;//5secprivatestaticintDISPLACEMENT=10;//10meters//UIelementsprivateTextViewlblLocation;privateButtonbtnShowLocation,btnStartLocationUpdates;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);lblLocation=(TextView)findViewById(R.id.lblLocation);btnShowLocation=(Button)findViewById(R.id.btnShowLocation);btnStartLocationUpdates=(Button)findViewById(R.id.btnLocationUpdates);//Firstweneedtocheckavailabilityofplayservicesif(checkPlayServices()){//BuildingtheGoogleApiclientbuildGoogleApiClient();}//ShowlocationbuttonclicklistenerbtnShowLocation.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){displayLocation();}});}/***MethodtodisplaythelocationonUI**/

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 8/16

    privatevoiddisplayLocation(){mLastLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);if(mLastLocation!=null){doublelatitude=mLastLocation.getLatitude();doublelongitude=mLastLocation.getLongitude();lblLocation.setText(latitude+","+longitude);}else{lblLocation.setText("(Couldn'tgetthelocation.Makesurelocationisenabledonthedevice)");}}/***Creatinggoogleapiclientobject**/protectedsynchronizedvoidbuildGoogleApiClient(){mGoogleApiClient=newGoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();}/***Methodtoverifygoogleplayservicesonthedevice**/privatebooleancheckPlayServices(){intresultCode=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);if(resultCode!=ConnectionResult.SUCCESS){if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RESOLUTION_REQUEST).show();}else{Toast.makeText(getApplicationContext(),"Thisdeviceisnotsupported.",Toast.LENGTH_LONG).show();finish();}returnfalse;}returntrue;}@OverrideprotectedvoidonStart(){super.onStart();if(mGoogleApiClient!=null){mGoogleApiClient.connect();}}@OverrideprotectedvoidonResume(){super.onResume();checkPlayServices();}/***Googleapicallbackmethods*/@OverridepublicvoidonConnectionFailed(ConnectionResultresult){Log.i(TAG,"Connectionfailed:ConnectionResult.getErrorCode()="+result.getErrorCode());}@OverridepublicvoidonConnected(Bundlearg0){//Onceconnectedwithgoogleapi,getthelocationdisplayLocation();}@OverridepublicvoidonConnectionSuspended(intarg0){mGoogleApiClient.connect();}}

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 9/16

    Receiving Location Updates

    9. In certain scenarios, your app might needs location updates periodically. Lets say you are building a direction app where user needs to be get updated whenever location is changed. In that case you need torequest for location updates. Doing the below changes, you will get the new location wherever location is changed.

    > Implement the activity from LocationListener which adds onLocationChanged() method.

    > Create LocationRequest object by calling createLocationRequest() method in onCreate() method upon checking the play services availability.

    > Add togglePeriodicLocationUpdates() method which toggles listening to location updates.

    > Start the location updates by calling startLocationUpdates() in onConnected() and onResume() methods.

    > Stop the location updates by calling stopLocationUpdates() in onStop().

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 10/16

    > startLocationUpdates() and stopLocationUpdates() methods are used to start/stop the location updates.

    > onLocationChanged() method will be triggered whenever the location is changed. Calling displayLocation() inside onLocationChanged will display new location data on the UI.

    MainActivity.javapublicclassMainActivityextendsActivityimplementsConnectionCallbacks,OnConnectionFailedListener,LocationListener{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Firstweneedtocheckavailabilityofplayservicesif(checkPlayServices()){createLocationRequest();}//TogglingtheperiodiclocationupdatesbtnStartLocationUpdates.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){togglePeriodicLocationUpdates();}});}@OverrideprotectedvoidonResume(){super.onResume();//Resumingtheperiodiclocationupdatesif(mGoogleApiClient.isConnected()&&mRequestingLocationUpdates){startLocationUpdates();}}@OverrideprotectedvoidonPause(){super.onPause();stopLocationUpdates();}/***Methodtotoggleperiodiclocationupdates**/privatevoidtogglePeriodicLocationUpdates(){if(!mRequestingLocationUpdates){//ChangingthebuttontextbtnStartLocationUpdates.setText(getString(R.string.btn_stop_location_updates));mRequestingLocationUpdates=true;//StartingthelocationupdatesstartLocationUpdates();Log.d(TAG,"Periodiclocationupdatesstarted!");}else{//ChangingthebuttontextbtnStartLocationUpdates.setText(getString(R.string.btn_start_location_updates));mRequestingLocationUpdates=false;//StoppingthelocationupdatesstopLocationUpdates();Log.d(TAG,"Periodiclocationupdatesstopped!");}}/***Creatinglocationrequestobject**/protectedvoidcreateLocationRequest(){mLocationRequest=newLocationRequest();mLocationRequest.setInterval(UPDATE_INTERVAL);mLocationRequest.setFastestInterval(FATEST_INTERVAL);mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 11/16

    After doing all the above changes, run and test the app. If your app is not getting location, follow below steps to debug the app.

    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);//10meters}/***Startingthelocationupdates**/protectedvoidstartLocationUpdates(){LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);}/***Stoppinglocationupdates*/protectedvoidstopLocationUpdates(){LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);}@OverridepublicvoidonConnected(Bundlearg0){//Onceconnectedwithgoogleapi,getthelocationdisplayLocation();if(mRequestingLocationUpdates){startLocationUpdates();}}@OverridepublicvoidonLocationChanged(Locationlocation){//AssignthenewlocationmLastLocation=location;Toast.makeText(getApplicationContext(),"Locationchanged!",Toast.LENGTH_SHORT).show();//DisplayingthenewlocationonUIdisplayLocation();}}

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 12/16

    3. Testing the App

    Below are the few key points should be kept in mind while testing the app.

    > Your device should have internet connection (Wifi or mobile 3G).

    > Location service should be enabled. Go to Settings => Location => Turn On.

    > When you run the app, if you are not able to get the location even though you have done above two steps, open any of googles location apps (maps) and come back to our app or just tap on START LOCATIONUPDATES.

    > If you are testing the periodic location updates, go out and take a short walk (few steps). You should see the locationChanged method calling by giving latest location coordinates.

    Complete Code:

    Below is the complete code of MainActivity.java

    MainActivity.javapackageinfo.androidhive.locationapi;importandroid.app.Activity;importandroid.location.Location;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.View;

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 13/16

    importandroid.widget.Button;importandroid.widget.TextView;importandroid.widget.Toast;importcom.google.android.gms.common.ConnectionResult;importcom.google.android.gms.common.GooglePlayServicesUtil;importcom.google.android.gms.common.api.GoogleApiClient;importcom.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;importcom.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;importcom.google.android.gms.location.LocationListener;importcom.google.android.gms.location.LocationRequest;importcom.google.android.gms.location.LocationServices;publicclassMainActivityextendsActivityimplementsConnectionCallbacks,OnConnectionFailedListener,LocationListener{//LogCattagprivatestaticfinalStringTAG=MainActivity.class.getSimpleName();privatefinalstaticintPLAY_SERVICES_RESOLUTION_REQUEST=1000;privateLocationmLastLocation;//GoogleclienttointeractwithGoogleAPIprivateGoogleApiClientmGoogleApiClient;//booleanflagtotoggleperiodiclocationupdatesprivatebooleanmRequestingLocationUpdates=false;privateLocationRequestmLocationRequest;//LocationupdatesintervalsinsecprivatestaticintUPDATE_INTERVAL=10000;//10secprivatestaticintFATEST_INTERVAL=5000;//5secprivatestaticintDISPLACEMENT=10;//10meters//UIelementsprivateTextViewlblLocation;privateButtonbtnShowLocation,btnStartLocationUpdates;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);lblLocation=(TextView)findViewById(R.id.lblLocation);btnShowLocation=(Button)findViewById(R.id.btnShowLocation);btnStartLocationUpdates=(Button)findViewById(R.id.btnLocationUpdates);//Firstweneedtocheckavailabilityofplayservicesif(checkPlayServices()){//BuildingtheGoogleApiclientbuildGoogleApiClient();createLocationRequest();}//ShowlocationbuttonclicklistenerbtnShowLocation.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){displayLocation();}});//TogglingtheperiodiclocationupdatesbtnStartLocationUpdates.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){togglePeriodicLocationUpdates();}});}@OverrideprotectedvoidonStart(){super.onStart();if(mGoogleApiClient!=null){mGoogleApiClient.connect();}}

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 14/16

    @OverrideprotectedvoidonResume(){super.onResume();checkPlayServices();//Resumingtheperiodiclocationupdatesif(mGoogleApiClient.isConnected()&&mRequestingLocationUpdates){startLocationUpdates();}}@OverrideprotectedvoidonStop(){super.onStop();if(mGoogleApiClient.isConnected()){mGoogleApiClient.disconnect();}}@OverrideprotectedvoidonPause(){super.onPause();stopLocationUpdates();}/***MethodtodisplaythelocationonUI**/privatevoiddisplayLocation(){mLastLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);if(mLastLocation!=null){doublelatitude=mLastLocation.getLatitude();doublelongitude=mLastLocation.getLongitude();lblLocation.setText(latitude+","+longitude);}else{lblLocation.setText("(Couldn'tgetthelocation.Makesurelocationisenabledonthedevice)");}}/***Methodtotoggleperiodiclocationupdates**/privatevoidtogglePeriodicLocationUpdates(){if(!mRequestingLocationUpdates){//ChangingthebuttontextbtnStartLocationUpdates.setText(getString(R.string.btn_stop_location_updates));mRequestingLocationUpdates=true;//StartingthelocationupdatesstartLocationUpdates();Log.d(TAG,"Periodiclocationupdatesstarted!");}else{//ChangingthebuttontextbtnStartLocationUpdates.setText(getString(R.string.btn_start_location_updates));mRequestingLocationUpdates=false;//StoppingthelocationupdatesstopLocationUpdates();Log.d(TAG,"Periodiclocationupdatesstopped!");}}/***Creatinggoogleapiclientobject**/protectedsynchronizedvoidbuildGoogleApiClient(){mGoogleApiClient=newGoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();}

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 15/16

    /***Creatinglocationrequestobject**/protectedvoidcreateLocationRequest(){mLocationRequest=newLocationRequest();mLocationRequest.setInterval(UPDATE_INTERVAL);mLocationRequest.setFastestInterval(FATEST_INTERVAL);mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);mLocationRequest.setSmallestDisplacement(DISPLACEMENT);}/***Methodtoverifygoogleplayservicesonthedevice**/privatebooleancheckPlayServices(){intresultCode=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);if(resultCode!=ConnectionResult.SUCCESS){if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RESOLUTION_REQUEST).show();}else{Toast.makeText(getApplicationContext(),"Thisdeviceisnotsupported.",Toast.LENGTH_LONG).show();finish();}returnfalse;}returntrue;}/***Startingthelocationupdates**/protectedvoidstartLocationUpdates(){LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);}/***Stoppinglocationupdates*/protectedvoidstopLocationUpdates(){LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);}/***Googleapicallbackmethods*/@OverridepublicvoidonConnectionFailed(ConnectionResultresult){Log.i(TAG,"Connectionfailed:ConnectionResult.getErrorCode()="+result.getErrorCode());}@OverridepublicvoidonConnected(Bundlearg0){//Onceconnectedwithgoogleapi,getthelocationdisplayLocation();if(mRequestingLocationUpdates){startLocationUpdates();}}@OverridepublicvoidonConnectionSuspended(intarg0){mGoogleApiClient.connect();}@OverridepublicvoidonLocationChanged(Locationlocation){//AssignthenewlocationmLastLocation=location;Toast.makeText(getApplicationContext(),"Locationchanged!",Toast.LENGTH_SHORT).show();//DisplayingthenewlocationonUIdisplayLocation();

  • 6/25/2015 AndroidLocationAPIusingGooglePlayServices

    http://www.androidhive.info/2015/02/androidlocationapiusinggoogleplayservices/ 16/16

    }}