Monday 8 June 2015

Android Location API Using Google Play Services (Fuesd Location API)

The Fused Location Provider intelligently manages the underlying location technology and gives us the best location according to our needs.
WHY USE
We could choose one of the location providers (network or GPS) and request location updates or set up proximity alert. But there were two main issues with this approach:
1. In case we need to define precise location, we had to switch between network and GPS location providers (as GPS doesn’t work indoors).
2. Proximity alerts were used to notify a user about proximity to a location, and this took its toll on the battery life.
ADVANTAGE OF USING THIS API
1. Simple APIs: Lets us specify high-level needs like “high accuracy” or “low power”, instead of having to worry about location providers.
2. Immediately available: Gives our apps immediate access to the best, most recent location.
3. Power-efficiency: Minimizes out app’s use of power. Based on all incoming location requests and available sensors, fused location provider chooses the most efficient way to meet those needs.
4. Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
Note : Make sure Google Play services is properly installed and working in our device. Please don’t test this location api in emulator because this api is not working in the emulator.
WAY TO USE
1. Import Google Play Services from android SDK (../sdk/extras/google/google_play_service/libproject/google-play-services_lib) as a library in our application.

2.
 Declare the permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Android has two location permissions, ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION. The permission we choose affects the accuracy of the location updates we receive. For example, If we request only coarse location permission, Location Services obfuscates the updated location to an accuracy that’s roughly equivalent to a city block.
Requesting ACCESS_FINE_LOCATION implies a request for ACCESS_COARSE_LOCATION.
3. There is two main class which are most important in this server
3.1 com.google.android.gms.location.LocationClient : Stores the current instantiation of the location client.
3.2 com.google.android.gms.location.LocationRequest : A data object that contains quality of service parameters for requests to the LocationClient.
4. Location service callbacks : Before we request location updates, we must first implement the interfaces that Location Services uses to communicate connection status to our app:
4.1 com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks: Specifies methods that Location Services calls when a location client is connected or disconnected.
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
}
4.2 com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener:Specifies a method that Location Services calls if an error occurs while attempting to connect the location client.

HOW TO USE
1. Connecting LocationClient to Google api. After connecting locationClient, we are able to get location.
2. Retrieving the current location
3. Retrieving the location update at particular time interval or particular distance or both.
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
During the Google IO presentation, a chart was presented showing effect of different priorities of the recognition algorithm as tested multiple times on Galaxy Nexus.
PriorityTypical location
update interval
Battery drain
per hour (%)
Accuracy
HIGH_ACCURACY5 seconds7.25%~10 meters
BALANCED_POWER20 seconds0.6%~40 meters
NO_POWERN/Asmall~1 mile

2. Retrieving the current location :
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)")
  }
}
The return value is the best, most recent location, based on the permissions our app requested and the currently-enabled location sensors.
Before we create the location client, implement the interfaces that Location Services uses to communicate with our app:
Reference : https://developer.android.com/training/location/retrieve-current.html
3. Retrieving Location Updates : To get periodic location updates from Location Services, we send a request using a location client. Depending on the form of the request, Location Services either invokes a callback method and passes in a Location object, or issues an Intent that contains the location in its extended data. The accuracy and frequency of the updates are affected by the location permissions we’ve requested and the parameters we pass to Location Services with the request.
@Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(),"Location changed!",Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
To Get Full Code:  Click Here