|
| 1 | +package com.hmkcode.locations; |
| 2 | + |
| 3 | +import com.google.android.gms.common.ConnectionResult; |
| 4 | +import com.google.android.gms.common.api.GoogleApiClient; |
| 5 | +import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; |
| 6 | +import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; |
| 7 | +import com.google.android.gms.location.LocationServices; |
| 8 | + |
| 9 | +import android.app.Activity; |
| 10 | +import android.location.Location; |
| 11 | +import android.os.Bundle; |
| 12 | +import android.widget.TextView; |
| 13 | +import android.widget.Toast; |
| 14 | + |
| 15 | + |
| 16 | +public class MainActivity extends Activity implements |
| 17 | + ConnectionCallbacks, OnConnectionFailedListener { |
| 18 | + |
| 19 | + GoogleApiClient mGoogleApiClient; |
| 20 | + Location mLastLocation; |
| 21 | + TextView tvLatlong; |
| 22 | + |
| 23 | + @Override |
| 24 | + protected void onCreate(Bundle savedInstanceState) { |
| 25 | + super.onCreate(savedInstanceState); |
| 26 | + setContentView(R.layout.activity_main); |
| 27 | + |
| 28 | + tvLatlong = (TextView) findViewById(R.id.tvLatlong); |
| 29 | + |
| 30 | + buildGoogleApiClient(); |
| 31 | + |
| 32 | + if(mGoogleApiClient!= null){ |
| 33 | + mGoogleApiClient.connect(); |
| 34 | + } |
| 35 | + else |
| 36 | + Toast.makeText(this, "Not connected...", Toast.LENGTH_SHORT).show(); |
| 37 | + |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public void onConnectionFailed(ConnectionResult arg0) { |
| 43 | + Toast.makeText(this, "Failed to connect...", Toast.LENGTH_SHORT).show(); |
| 44 | + |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public void onConnected(Bundle arg0) { |
| 49 | + |
| 50 | + mLastLocation = LocationServices.FusedLocationApi.getLastLocation( |
| 51 | + mGoogleApiClient); |
| 52 | + |
| 53 | + if (mLastLocation != null) { |
| 54 | + tvLatlong.setText("Latitude: "+ String.valueOf(mLastLocation.getLatitude())+" - Longitude: "+ |
| 55 | + String.valueOf(mLastLocation.getLongitude())); |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + @Override |
| 61 | + public void onConnectionSuspended(int arg0) { |
| 62 | + Toast.makeText(this, "Connection suspended...", Toast.LENGTH_SHORT).show(); |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + protected synchronized void buildGoogleApiClient() { |
| 67 | + mGoogleApiClient = new GoogleApiClient.Builder(this) |
| 68 | + .addConnectionCallbacks(this) |
| 69 | + .addOnConnectionFailedListener(this) |
| 70 | + .addApi(LocationServices.API) |
| 71 | + .build(); |
| 72 | + } |
| 73 | +} |
0 commit comments