10:47 AM
0
To use GoogleApiClient, you have to use google play services library in your project. Questions may arise in your mind that what is google play services? Well, Google Play services provides you with easy access to Google services and is tightly integrated with the Android OS. Easy-to-use client libraries are provided for each service that let you implement the functionality you want easier and faster. google play services gives your apps more features to attract users on a wider range of devices. With Google Play services, your app can take advantage of the latest, Google-powered features such as Maps, Google+, and more, with automatic platform updates distributed as an APK through the Google Play store. This makes it faster for your users to receive updates and easier for you to integrate the newest that Google has to offer. All products in Google Play services share a common authorization API that leverages the existing Google accounts on the device. You and your users have a consistent and safe way to grant and receive OAuth2 access tokens to Google services. Devices running Android 2.3 or higher that have the Google Play Store app will automatically receive updates to Google Play services. Enhance your app with the most recent version of Google Play services without worrying about your users’ Android version.
Now comes to the use of GoogleApiClient, what is that and how it will help us? Lets dig into it, GoogleApiClient is the main entry point of using googleplayservices.
GoogleApiClient is used with a variety of static methods. Some of these methods require that GoogleApiClient be connected, some will queue up calls before GoogleApiClient is connected; check the specific API documentation to determine whether you need to be connected.
Before any operation is executed, the GoogleApiClient must be connected using the connect() method. The client is not considered connected until the onConnected(Bundle) callback has been called.
When your app is done using this client, call disconnect(), even if the async result from connect() has not yet been delivered.
You should instantiate a client object in your Activity’s onCreate(Bundle) method and then call connect() in onStart() and disconnect() in onStop(), regardless of the state.

Step-01: Our first step will be instantiate the client object in onCreate() method of the activity. We can do that in the way like below code:


mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
Do not forget to declare GoogleApiClient what is mGoogleApiClient here
To get the location update, we need LocationRequest object which will be used to give some properties like what is the interval to get the update location and what is the priority for the request. So what we have to do, We will declare a LocationRequest variable called mLocationRequest. we will instantiate it with our class variable and set properties inside of the onCreate() method.
LocationRequest mLocationRequest=new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Now we have to connect with GoogleApiClient. We will place this request inside of our onStart() method of the activity.
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();//be connected with GoogleApiClient
}
If the connection is successful it will call the onConnected() method or if the connection is failed, it will call onConnectionFailed() or else it will call onConnectionSuspended() method.
@Override
public void onConnected(Bundle bundle) {
updateUI(); //this method will place a request for the last known location and update the UI
if(requestingLocationUpdate){
startLocationUpdate();// this will be calling to get the update location frequently based on user requirements
}
}
So How to get the last location? well here is the method to get it:
Location lastLocation= LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
We got the last know location above but what about our update location? This is the way to get that also
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
it will return update location continuously but where this location will go to update the UI? Well it will go the method onLocationChanged() method where you can update your update location. Why and How? Look at the requestLocationUpdates(.., … ,…) method, it takes three parameters. These are GoogleApiClient, LocationRequest and LocationListener. For LocationListener, i passed “this”. What I mean by that is go to the LocationListener interface of the Activity class which OnLocationChanged in our case here.
Now come back to OnLocationChanged method. It has one parameter which the update location. This parameter comes from the method “requestLocationUpdates”. Now you update your UI for this update location or whatever you want to do. So code snippet will be something like this:

@Override
public void onLocationChanged(Location location) {
locationUp=location;
updateView();
}

Full Code:

Activity:

public class MainActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
TextView tvLocation;
TextView tvLocationUpdate;
GoogleApiClient mGoogleApiClient;
GoogleMap map ;
Location locationUp;
LocationRequest mLocationRequest=new LocationRequest();
boolean requestingLocationUpdate=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLoc);//last location
tvLocationUpdate=(TextView)findViewById(R.id.tvLocUpdate);//update location
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();//be connected with GoogleApiClient
}
@Override
public void onConnected(Bundle bundle) {
updateUI();
if(requestingLocationUpdate){
startLocationUpdate();//trying to get the update location
}
}
private void startLocationUpdate() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}
private void updateUI() {
tvLocation.setText(“Last Known Location:”+String.valueOf(getLocation().getLatitude())+String.valueOf(getLocation().getLongitude()));
}
private Location getLocation() {
Location lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
return lastKnownLocation;
}
@Override
public void onConnectionSuspended(int i) {
Log.d(“result:”, “connection has been suspended”);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(“result:”,”not connected with GoogleApiClient”);
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdate();//when activity is on pause, need to stop the location update since we
//do not need that any more
}
private void stopLocationUpdate() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);//stopping the update location
}
//no need to use googleplayservices
@Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();//disconnect the GoogleApiClient from the google play services
}
@Override
protected void onResume() {
super.onResume();
if(mGoogleApiClient.isConnected()){
startLocationUpdate();// since we need to get the update location continuously like gps
//when activity is in foreground(resume), then we have to request to get update location
//here alos
}
}
//to get the location change
@Override
public void onLocationChanged(Location location) {
locationUp=location;//this location is the update location,
// came from the requestLocationUpdate() method’s interface
updateView();//put your value in the text or whatever you want to do
}
private void updateView() {
tvLocationUpdate.setText(“Update Location:”+String.valueOf(locationUp.getLatitude())+String.valueOf(locationUp.getLongitude()));
}
}

My Layout:

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<TextView
android:id=”@+id/tvLoc”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_centerInParent=”true”/>
<TextView
android:id=”@+id/tvLocUpdate”
android:layout_below=”@id/tvLoc”
android:layout_marginTop=”10dp”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”/>
</RelativeLayout>

Output:

location
You can find the whole code from here:
https://github.com/nanofaroque/GoogleApiClientTesting


0 comments:

Post a Comment