keyurmehta

source code Location

Mar 31st, 2016
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. public class Main2Activity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
  2.         GoogleApiClient.OnConnectionFailedListener, LocationListener {
  3.  
  4.     Location mLastLocation;
  5.     private GoogleApiClient mGoogleApiClient;
  6.     private LocationRequest mLocationRequest;
  7.     String lat, lon;
  8.  
  9.     @Override
  10.     protected void onCreate(Bundle savedInstanceState) {
  11.         super.onCreate(savedInstanceState);
  12.         setContentView(R.layout.activity_main2);
  13.  
  14.         buildGoogleApiClient();
  15.     }
  16.  
  17.  
  18.     @Override
  19.     public void onConnected(Bundle bundle) {
  20.         mLocationRequest = LocationRequest.create();
  21.         mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  22.         mLocationRequest.setInterval(100); // Update location every second
  23.  
  24.         LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
  25.  
  26.  
  27.         mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
  28.                 mGoogleApiClient);
  29.         if (mLastLocation != null) {
  30.             lat = String.valueOf(mLastLocation.getLatitude());
  31.             lon = String.valueOf(mLastLocation.getLongitude());
  32.  
  33.         }
  34.     }
  35.  
  36.     @Override
  37.     public void onConnectionSuspended(int i) {
  38.  
  39.     }
  40.  
  41.     @Override
  42.     public void onLocationChanged(Location location) {
  43.         lat = String.valueOf(location.getLatitude());
  44.         lon = String.valueOf(location.getLongitude());
  45.  
  46.         Log.d("System out", "Latitude:"+lat+"::Longitude:"+lon);
  47.     }
  48.  
  49.     @Override
  50.     public void onConnectionFailed(ConnectionResult connectionResult) {
  51.         buildGoogleApiClient();
  52.     }
  53.  
  54.     synchronized void buildGoogleApiClient() {
  55.         mGoogleApiClient = new GoogleApiClient.Builder(this)
  56.                 .addConnectionCallbacks(this)
  57.                 .addOnConnectionFailedListener(this)
  58.                 .addApi(LocationServices.API)
  59.                 .build();
  60.  
  61.  
  62.     }
  63.  
  64.     @Override
  65.     protected void onStart() {
  66.         super.onStart();
  67.         mGoogleApiClient.connect();
  68.     }
  69.  
  70.     @Override
  71.     protected void onDestroy() {
  72.         super.onDestroy();
  73.         mGoogleApiClient.disconnect();
  74.     }
  75. }
Add Comment
Please, Sign In to add comment