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:
Do not forget to declare GoogleApiClient what is mGoogleApiClient here
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
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();Now we have to connect with GoogleApiClient. We will place this request inside of our onStart() method of the activity.
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
@OverrideIf 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.
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();//be connected with GoogleApiClient
}
@OverrideSo How to get the last location? well here is the method to get it:
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
}
}
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”
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:
You can find the whole code from here:https://github.com/nanofaroque/GoogleApiClientTesting
0 comments:
Post a Comment