Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LocationTracker extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, SensorEventListener {
- // LogCat tag
- private static final String TAG = "LocationTracker";
- private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
- private static int UPDATE_INTERVAL = 10000; // 10 sec
- private static int FASTEST_INTERVAL = UPDATE_INTERVAL/2; // 5 sec
- private Context context;
- private SharedPreferences sp;
- // Location updates intervals in sec
- private Location mLastLocation;
- // Google client to interact with Google API
- private GoogleApiClient mGoogleApiClient;
- private LocationRequest mLocationRequest;
- private double latitude, longitude, altitude, distance;
- private boolean firstLocation = false;
- private float pressure, heading, speed;
- public LocationTracker(Context ctx, boolean firstLocation) {
- context = ctx;
- sp = context.getSharedPreferences(Utility.SHARED_PREFS, MODE_PRIVATE);
- this.firstLocation = firstLocation;
- // First we need to check availability of play services
- if (checkPlayServices()) {
- buildGoogleApiClient();
- if (mGoogleApiClient != null)
- mGoogleApiClient.connect();
- }
- }
- @Override
- public void onConnectionSuspended(int i) {
- mGoogleApiClient.connect();
- }
- @Override
- public void onConnectionFailed(ConnectionResult connectionResult) {
- }
- /**
- * Creating google api client object
- */
- protected synchronized void buildGoogleApiClient() {
- mGoogleApiClient = new GoogleApiClient.Builder(context)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API).build();
- createLocationRequest();
- }
- /**
- * Method to verify google play services on the device
- */
- private boolean checkPlayServices() {
- int resultCode = GooglePlayServicesUtil
- .isGooglePlayServicesAvailable(context);
- if (resultCode != ConnectionResult.SUCCESS) {
- if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
- Utility.showLog(TAG, "Something went wrong with error code :" + resultCode);
- else
- Utility.showLog(TAG,
- "This device is not supported.");
- // stopLocationUpdates();
- return false;
- }
- return true;
- }
- /**
- * Creating home_last_location request object
- */
- protected void createLocationRequest() {
- mLocationRequest = new LocationRequest();
- mLocationRequest.setInterval(UPDATE_INTERVAL);
- mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
- mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
- }
- /**
- * Starting the home_last_location updates
- */
- public void startLocationUpdates() {
- Utility.showLog(TAG, "Starting Location Updates");
- // Only for 6.0 and above devices
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if ((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED))
- LocationServices.FusedLocationApi.requestLocationUpdates(
- mGoogleApiClient, mLocationRequest, this);
- } else
- LocationServices.FusedLocationApi.requestLocationUpdates(
- mGoogleApiClient, mLocationRequest, this);
- }
- /**
- * Stopping home_last_location updates
- */
- public void stopLocationUpdates() {
- Utility.showLog(TAG, "Stopping Location Updates");
- if (mGoogleApiClient != null) {
- if (mGoogleApiClient.isConnected())
- LocationServices.FusedLocationApi.removeLocationUpdates(
- mGoogleApiClient, this);
- if (mGoogleApiClient.isConnected())
- mGoogleApiClient.disconnect();
- }
- stopSelf();
- }
- /**
- * Function to get latitude
- */
- public double getLatitude() {
- // return latitude
- return latitude;
- }
- /**
- * Function to get longitude
- */
- public double getLongitude() {
- // return longitude
- return longitude;
- }
- /**
- * Function to get Altitude
- */
- public double getAltitude() {
- // return altitude
- return altitude;
- }
- /**
- * Function to get Heading
- */
- public double getHeading() {
- return heading;
- }
- public double getDistance() {
- return distance;
- }
- @Override
- public void onConnected(Bundle bundle) {
- Utility.showLog(TAG, "Google API Connected");
- // Once connected with google api, get the Last Location
- updateLocation();
- startLocationUpdates();
- }
- @Override
- public void onLocationChanged(Location location) {
- // Assign the new home_last_location
- mLastLocation = location;
- updateLocation();
- }
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- /**
- * Method to display the home_last_location on UI
- */
- private void updateLocation() {
- // Only for 6.0 and above devices
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if ((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED))
- mLastLocation = LocationServices.FusedLocationApi
- .getLastLocation(mGoogleApiClient);
- } else
- mLastLocation = LocationServices.FusedLocationApi
- .getLastLocation(mGoogleApiClient);
- if (mLastLocation != null) {
- if (firstLocation) {
- sp.edit().putString("last_latitude", String.valueOf(mLastLocation.getLatitude())).commit();
- sp.edit().putString("last_longitude", String.valueOf(mLastLocation.getLongitude())).commit();
- sp.edit().putLong("last_location_time", System.currentTimeMillis()).commit();
- firstLocation = false;
- }
- latitude = mLastLocation.getLatitude();
- longitude = mLastLocation.getLongitude();
- heading = mLastLocation.getBearing();
- altitude = mLastLocation.getAltitude();
- } else
- Utility.showLog(TAG, "Couldn't get the location. Make sure location is enabled on the device");
- }
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- sensorManager.unregisterListener(this, magnetometerSensor);
- sensorManager.unregisterListener(this, accelerometerSensor);
- sensorManager.unregisterListener(this, pressureSensor);
- Utility.showLog(TAG, "Location Tracker Stopped");
- }
- /**
- * Function to get Speed
- */
- public double getSpeed() {
- double previousLatitude = Double.parseDouble(sp.getString("last_latitude", "0.0"));
- double previousLongitude = Double.parseDouble(sp.getString("last_longitude", "0.0"));
- Utility.showLog(TAG, "Old Latitude :" + previousLatitude);
- Utility.showLog(TAG, "Old Longitude :" + previousLongitude);
- Utility.showLog(TAG, "New Latitude :" + latitude);
- Utility.showLog(TAG, "New Longitude :" + longitude);
- Location sourceLocation = new Location("A");
- sourceLocation.setLatitude(previousLatitude);
- sourceLocation.setLongitude(previousLongitude);
- Location destinationLocation = new Location("B");
- destinationLocation.setLatitude(latitude);
- destinationLocation.setLongitude(longitude);
- double distanceTo = sourceLocation.distanceTo(destinationLocation);
- distance = distanceTo;
- Utility.showLog(TAG, "Distance =" + distanceTo);
- long differenceInTime = (System.currentTimeMillis() - sp.getLong("last_location_time", 0)) / 1000;
- double mps = distanceTo / differenceInTime;
- double kph = (mps * 3600) / 1000;
- return kph;
- }
- }
Add Comment
Please, Sign In to add comment