Guest User

Untitled

a guest
Feb 22nd, 2016
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.75 KB | None | 0 0
  1. public class LocationTracker extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, SensorEventListener {
  2.  
  3.     // LogCat tag
  4.     private static final String TAG = "LocationTracker";
  5.  
  6.     private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
  7.  
  8.     private static int UPDATE_INTERVAL = 10000; // 10 sec
  9.     private static int FASTEST_INTERVAL = UPDATE_INTERVAL/2; // 5 sec
  10.  
  11.     private Context context;
  12.     private SharedPreferences sp;
  13.  
  14.     // Location updates intervals in sec
  15.     private Location mLastLocation;
  16.     // Google client to interact with Google API
  17.     private GoogleApiClient mGoogleApiClient;
  18.     private LocationRequest mLocationRequest;
  19.  
  20.     private double latitude, longitude, altitude, distance;
  21.     private boolean firstLocation = false;
  22.     private float pressure, heading, speed;
  23.  
  24.     public LocationTracker(Context ctx, boolean firstLocation) {
  25.  
  26.         context = ctx;
  27.  
  28.         sp = context.getSharedPreferences(Utility.SHARED_PREFS, MODE_PRIVATE);
  29.         this.firstLocation = firstLocation;
  30.  
  31.         // First we need to check availability of play services
  32.         if (checkPlayServices()) {
  33.  
  34.             buildGoogleApiClient();
  35.  
  36.             if (mGoogleApiClient != null)
  37.                 mGoogleApiClient.connect();
  38.         }
  39.  
  40.     }
  41.  
  42.  
  43.     @Override
  44.     public void onConnectionSuspended(int i) {
  45.         mGoogleApiClient.connect();
  46.     }
  47.  
  48.     @Override
  49.     public void onConnectionFailed(ConnectionResult connectionResult) {
  50.  
  51.     }
  52.  
  53.     /**
  54.      * Creating google api client object
  55.      */
  56.     protected synchronized void buildGoogleApiClient() {
  57.  
  58.         mGoogleApiClient = new GoogleApiClient.Builder(context)
  59.                 .addConnectionCallbacks(this)
  60.                 .addOnConnectionFailedListener(this)
  61.                 .addApi(LocationServices.API).build();
  62.  
  63.         createLocationRequest();
  64.     }
  65.  
  66.     /**
  67.      * Method to verify google play services on the device
  68.      */
  69.     private boolean checkPlayServices() {
  70.  
  71.         int resultCode = GooglePlayServicesUtil
  72.                 .isGooglePlayServicesAvailable(context);
  73.  
  74.         if (resultCode != ConnectionResult.SUCCESS) {
  75.  
  76.             if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
  77.                 Utility.showLog(TAG, "Something went wrong with error code :" + resultCode);
  78.             else
  79.                 Utility.showLog(TAG,
  80.                         "This device is not supported.");
  81.  
  82.             // stopLocationUpdates();
  83.             return false;
  84.         }
  85.  
  86.         return true;
  87.     }
  88.  
  89.  
  90.     /**
  91.      * Creating home_last_location request object
  92.      */
  93.     protected void createLocationRequest() {
  94.  
  95.         mLocationRequest = new LocationRequest();
  96.         mLocationRequest.setInterval(UPDATE_INTERVAL);
  97.         mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
  98.         mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  99.  
  100.     }
  101.  
  102.     /**
  103.      * Starting the home_last_location updates
  104.      */
  105.     public void startLocationUpdates() {
  106.  
  107.  
  108.         Utility.showLog(TAG, "Starting Location Updates");
  109.  
  110.  
  111.         // Only for 6.0 and above devices
  112.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  113.  
  114.             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))
  115.                 LocationServices.FusedLocationApi.requestLocationUpdates(
  116.                         mGoogleApiClient, mLocationRequest, this);
  117.         } else
  118.             LocationServices.FusedLocationApi.requestLocationUpdates(
  119.                     mGoogleApiClient, mLocationRequest, this);
  120.     }
  121.  
  122.     /**
  123.      * Stopping home_last_location updates
  124.      */
  125.     public void stopLocationUpdates() {
  126.  
  127.         Utility.showLog(TAG, "Stopping Location Updates");
  128.  
  129.         if (mGoogleApiClient != null) {
  130.  
  131.             if (mGoogleApiClient.isConnected())
  132.                 LocationServices.FusedLocationApi.removeLocationUpdates(
  133.                         mGoogleApiClient, this);
  134.  
  135.             if (mGoogleApiClient.isConnected())
  136.                 mGoogleApiClient.disconnect();
  137.  
  138.         }
  139.         stopSelf();
  140.  
  141.     }
  142.  
  143.  
  144.     /**
  145.      * Function to get latitude
  146.      */
  147.     public double getLatitude() {
  148.  
  149.         // return latitude
  150.         return latitude;
  151.     }
  152.  
  153.     /**
  154.      * Function to get longitude
  155.      */
  156.     public double getLongitude() {
  157.  
  158.         // return longitude
  159.         return longitude;
  160.     }
  161.  
  162.     /**
  163.      * Function to get Altitude
  164.      */
  165.     public double getAltitude() {
  166.  
  167.         // return altitude
  168.         return altitude;
  169.     }
  170.  
  171.  
  172.     /**
  173.      * Function to get Heading
  174.      */
  175.     public double getHeading() {
  176.  
  177.         return heading;
  178.     }
  179.  
  180.     public double getDistance() {
  181.  
  182.         return distance;
  183.     }
  184.  
  185.     @Override
  186.     public void onConnected(Bundle bundle) {
  187.  
  188.         Utility.showLog(TAG, "Google API Connected");
  189.  
  190.         // Once connected with google api, get the Last Location
  191.         updateLocation();
  192.  
  193.         startLocationUpdates();
  194.     }
  195.  
  196.     @Override
  197.     public void onLocationChanged(Location location) {
  198.  
  199.         // Assign the new home_last_location
  200.         mLastLocation = location;
  201.         updateLocation();
  202.  
  203.     }
  204.  
  205.     @Override
  206.     public IBinder onBind(Intent intent) {
  207.         return null;
  208.     }
  209.  
  210.     /**
  211.      * Method to display the home_last_location on UI
  212.      */
  213.     private void updateLocation() {
  214.  
  215.         // Only for 6.0 and above devices
  216.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  217.  
  218.             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))
  219.                 mLastLocation = LocationServices.FusedLocationApi
  220.                         .getLastLocation(mGoogleApiClient);
  221.  
  222.         } else
  223.             mLastLocation = LocationServices.FusedLocationApi
  224.                     .getLastLocation(mGoogleApiClient);
  225.  
  226.         if (mLastLocation != null) {
  227.  
  228.             if (firstLocation) {
  229.  
  230.  
  231.                 sp.edit().putString("last_latitude", String.valueOf(mLastLocation.getLatitude())).commit();
  232.                 sp.edit().putString("last_longitude", String.valueOf(mLastLocation.getLongitude())).commit();
  233.                 sp.edit().putLong("last_location_time", System.currentTimeMillis()).commit();
  234.  
  235.  
  236.                 firstLocation = false;
  237.             }
  238.  
  239.             latitude = mLastLocation.getLatitude();
  240.             longitude = mLastLocation.getLongitude();
  241.  
  242.             heading = mLastLocation.getBearing();
  243.             altitude = mLastLocation.getAltitude();
  244.  
  245.         } else
  246.             Utility.showLog(TAG, "Couldn't get the location. Make sure location is enabled on the device");
  247.     }
  248.  
  249.  
  250.  
  251.  
  252.     @Override
  253.     public void onAccuracyChanged(Sensor sensor, int accuracy) {
  254.  
  255.  
  256.     }
  257.  
  258.  
  259.     @Override
  260.     public void onDestroy() {
  261.         super.onDestroy();
  262.  
  263.         sensorManager.unregisterListener(this, magnetometerSensor);
  264.         sensorManager.unregisterListener(this, accelerometerSensor);
  265.         sensorManager.unregisterListener(this, pressureSensor);
  266.  
  267.         Utility.showLog(TAG, "Location Tracker Stopped");
  268.     }
  269.  
  270.     /**
  271.      * Function to get Speed
  272.      */
  273.  
  274.     public double getSpeed() {
  275.  
  276.  
  277.         double previousLatitude = Double.parseDouble(sp.getString("last_latitude", "0.0"));
  278.         double previousLongitude = Double.parseDouble(sp.getString("last_longitude", "0.0"));
  279.  
  280.         Utility.showLog(TAG, "Old Latitude :" + previousLatitude);
  281.         Utility.showLog(TAG, "Old Longitude :" + previousLongitude);
  282.  
  283.         Utility.showLog(TAG, "New Latitude :" + latitude);
  284.         Utility.showLog(TAG, "New Longitude :" + longitude);
  285.  
  286.         Location sourceLocation = new Location("A");
  287.         sourceLocation.setLatitude(previousLatitude);
  288.         sourceLocation.setLongitude(previousLongitude);
  289.  
  290.         Location destinationLocation = new Location("B");
  291.         destinationLocation.setLatitude(latitude);
  292.         destinationLocation.setLongitude(longitude);
  293.  
  294.  
  295.         double distanceTo = sourceLocation.distanceTo(destinationLocation);
  296.  
  297.         distance = distanceTo;
  298.  
  299.         Utility.showLog(TAG, "Distance =" + distanceTo);
  300.  
  301.         long differenceInTime = (System.currentTimeMillis() - sp.getLong("last_location_time", 0)) / 1000;
  302.  
  303.         double mps = distanceTo / differenceInTime;
  304.         double kph = (mps * 3600) / 1000;
  305.  
  306.         return kph;
  307.     }
  308. }
Add Comment
Please, Sign In to add comment