Advertisement
Guest User

gps

a guest
Apr 15th, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.81 KB | None | 0 0
  1. package com.apps.taxi.iridedriverapp.Services;
  2.  
  3. import android.app.Service;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.SharedPreferences;
  7. import android.location.Location;
  8. import android.location.LocationListener;
  9. import android.location.LocationManager;
  10. import android.os.Bundle;
  11. import android.os.IBinder;
  12. import android.os.PowerManager;
  13. import android.preference.PreferenceManager;
  14. import android.util.Log;
  15. import android.widget.Toast;
  16.  
  17. import com.android.volley.Request;
  18. import com.android.volley.RequestQueue;
  19. import com.android.volley.Response;
  20. import com.android.volley.VolleyError;
  21. import com.android.volley.VolleyLog;
  22. import com.android.volley.toolbox.JsonObjectRequest;
  23. import com.android.volley.toolbox.StringRequest;
  24. import com.android.volley.toolbox.Volley;
  25. import com.apps.taxi.iridedriverapp.config.AppsDriverApplication;
  26. import com.apps.taxi.iridedriverapp.models.DRIVER;
  27. import com.apps.taxi.iridedriverapp.models.History;
  28. import com.apps.taxi.iridedriverapp.serviceHandler.GPSTracker;
  29. import com.apps.taxi.iridedriverapp.utils.Utills;
  30. import com.google.android.gms.common.ConnectionResult;
  31. import com.google.android.gms.common.GooglePlayServicesUtil;
  32. import com.google.android.gms.common.api.GoogleApiClient;
  33. import com.google.android.gms.location.LocationRequest;
  34. import com.google.android.gms.location.LocationServices;
  35.  
  36. import org.json.JSONException;
  37. import org.json.JSONObject;
  38.  
  39. /**
  40.  * Created by ARBI on 23/02/2016.
  41.  */
  42. public class LocationServicess extends Service
  43. {
  44.     public static final String BROADCAST_ACTION = "Hello World";
  45.     private static final int TWO_MINUTES = 1000;
  46.     public LocationManager locationManager;
  47.     public MyLocationListener listener;
  48.     public Location previousBestLocation = null;
  49.     GPSTracker gpsTracker;
  50.     Intent intent;
  51.     int counter = 0;
  52.     double travelDistance=0;
  53.     String locationUpdationURL="";
  54.  
  55.     Location LastLocation;
  56.     Location newLocation;
  57.     Location mLastLocation;
  58.  
  59.     // Fused Apis
  60.     private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
  61.  
  62.     // Google client to interact with Google API
  63.     private GoogleApiClient mGoogleApiClient;
  64.  
  65.     // boolean flag to toggle periodic location updates
  66.     private boolean mRequestingLocationUpdates = false;
  67.  
  68.     private LocationRequest mLocationRequest;
  69.  
  70.     // Location updates intervals in sec
  71.     private static int UPDATE_INTERVAL = 10000; // 20 sec
  72.     private static int FATEST_INTERVAL = 10000; // 20 sec
  73.     private static int DISPLACEMENT = 10; // 10 meters
  74.  
  75.  
  76.     PowerManager powerManager;
  77.     PowerManager.WakeLock wakeLock;
  78.  
  79.     @Override
  80.     public void onCreate()
  81.     {
  82.         super.onCreate();
  83.         gpsTracker = new GPSTracker(this);
  84.         intent = new Intent(BROADCAST_ACTION);
  85.         if(!get_TravelDistance().equals("")){
  86.             travelDistance=Double.parseDouble(get_TravelDistance());
  87.         }
  88.         powerManager = (PowerManager) getSystemService(POWER_SERVICE);
  89.         wakeLock= powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
  90.                 "MyWakelockTag");
  91.         wakeLock.acquire();
  92.     }
  93.  
  94.     @Override
  95.     public int onStartCommand(Intent intent, int flags, int startId) {
  96.         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  97.         listener = new MyLocationListener();
  98.         locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, listener);
  99.         locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, listener);
  100.         if(gpsTracker.getLocation()!=null && get_ride_status()) {
  101.             LastLocation = gpsTracker.getLocation();
  102.             newLocation  = gpsTracker.getLocation();
  103.         }
  104.         if(!get_TravelDistance().equals("")){
  105.             travelDistance=Double.parseDouble(get_TravelDistance());
  106.         }
  107. //        return START_STICKY;
  108.         return super.onStartCommand(intent, flags, startId);
  109.  
  110.     }
  111.  
  112.     @Override
  113.     public IBinder onBind(Intent intent)
  114.     {
  115.         return null;
  116.     }
  117.  
  118.     protected boolean isBetterLocation(Location location, Location currentBestLocation) {
  119.         if (currentBestLocation == null) {
  120.             // A new location is always better than no location
  121.             return true;
  122.         }
  123.  
  124.         // Check whether the new location fix is newer or older
  125.         long timeDelta = location.getTime() - currentBestLocation.getTime();
  126.         boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
  127.         boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
  128.         boolean isNewer = timeDelta > 0;
  129.  
  130.         // If it's been more than two minutes since the current location, use the new location
  131.         // because the user has likely moved
  132.         if (isSignificantlyNewer) {
  133.             return true;
  134.             // If the new location is more than two minutes older, it must be worse
  135.         } else if (isSignificantlyOlder) {
  136.             return false;
  137.         }
  138.  
  139.         // Check whether the new location fix is more or less accurate
  140.         int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
  141.         boolean isLessAccurate = accuracyDelta > 5;
  142.         boolean isMoreAccurate = accuracyDelta < 5;
  143.         boolean isSignificantlyLessAccurate = accuracyDelta > 200;
  144.  
  145.         // Check if the old and new location are from the same provider
  146.         boolean isFromSameProvider = isSameProvider(location.getProvider(),
  147.                 currentBestLocation.getProvider());
  148.  
  149.         // Determine location quality using a combination of timeliness and accuracy
  150.         if (isMoreAccurate) {
  151.             return true;
  152.         } else if (isNewer && !isLessAccurate) {
  153.             return true;
  154.         } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
  155.             return true;
  156.         }
  157.         return false;
  158.     }
  159.  
  160.  
  161.  
  162.     /** Checks whether two providers are the same */
  163.     private boolean isSameProvider(String provider1, String provider2) {
  164.         if (provider1 == null) {
  165.             return provider2 == null;
  166.         }
  167.         return provider1.equals(provider2);
  168.     }
  169.  
  170.  
  171.  
  172.     @Override
  173.     public void onDestroy() {
  174.         // handler.removeCallbacks(sendUpdatesToUI);
  175.         super.onDestroy();
  176.         listener.stopUpdateLocation();
  177.         Log.v("STOP_SERVICE", "DONE");
  178.         locationManager.removeUpdates(listener);
  179.         wakeLock.release();
  180.     }
  181.  
  182.     public static Thread performOnBackgroundThread(final Runnable runnable) {
  183.         final Thread t = new Thread() {
  184.             @Override
  185.             public void run() {
  186.                 try {
  187.                     runnable.run();
  188.                 } finally {
  189.  
  190.                 }
  191.             }
  192.         };
  193.         t.start();
  194.         return t;
  195.     }
  196.  
  197.  
  198.  
  199.  
  200.     public class MyLocationListener implements LocationListener,GoogleApiClient.ConnectionCallbacks,
  201.             GoogleApiClient.OnConnectionFailedListener {
  202.  
  203.  
  204.         public MyLocationListener(){
  205.             buildGoogleApiClient();
  206.             createLocationRequest();
  207.  
  208.             if (mGoogleApiClient != null) {
  209.                 mGoogleApiClient.connect();
  210.             }
  211.             displayLocation();
  212.  
  213.  
  214.  
  215.         }
  216.         public void onLocationChanged(final Location loc) {
  217.             Log.i("******", "Location changed");
  218.  
  219.             mLastLocation=loc;
  220.             if (loc != null &&newLocation!=null&&LastLocation!=null) {
  221.                 newLocation.setLatitude(loc.getLatitude());
  222.                 newLocation.setLongitude(loc.getLongitude());
  223.                 if ( get_ride_status() && LastLocation.getLatitude() != loc.getLatitude() && LastLocation.getLongitude() != loc.getLongitude()) {
  224.                         double newDistance =  LastLocation.distanceTo(loc);
  225.                         Log.e("newDistance-------",""+newDistance);
  226.                         int suitableMeter = 20;
  227.                         if (loc.getAccuracy() <= suitableMeter) {
  228.                             LastLocation = loc;
  229.                             set_LastLocationLongitude((long)loc.getLongitude());
  230.                             set_LastLocationLatitude((long)loc.getLatitude());
  231.                             newDistance = newDistance / 900;
  232.                             Log.e("newDistance/////////",""+newDistance);
  233.                             travelDistance = travelDistance + newDistance;
  234. //                            Toast.makeText(getApplicationContext(), "" + travelDistance + " KM", Toast.LENGTH_SHORT).show();
  235.                             set_TravelDistance(travelDistance);
  236.                         }
  237.                     loc.getLatitude();
  238.                     loc.getLongitude();
  239.                     intent.putExtra("Latitude", loc.getLatitude());
  240.                     intent.putExtra("Longitude", loc.getLongitude());
  241.                     intent.putExtra("Provider", loc.getProvider());
  242.                     sendBroadcast(intent);
  243.                     locationUpdationURL = "http://appstaxi.com/mappservicesia/index.php?command=update_driver_location&" +
  244.                             "user_id=" + get_DriverID() + "&" +
  245.                             "longitude=" + loc.getLongitude() + "&" +
  246.                             "latitude=" + loc.getLatitude() + "&" +
  247.                             "distance_travelled=" + get_TravelDistance();
  248.                 }
  249.             }
  250.             if(Utills.isOnline(getApplicationContext())) {
  251.                 makeJsonPostRequest();
  252.             }
  253.             displayLocation();
  254.         }
  255.  
  256.         public void onProviderDisabled(String provider)
  257.         {
  258. //            Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
  259.         }
  260.  
  261.         public void onProviderEnabled(String provider)
  262.         {
  263. //            Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
  264.         }
  265.  
  266.         public void onStatusChanged(String provider, int status, Bundle extras)
  267.         {
  268.  
  269.         }
  270.         /**
  271.          * Google api callback methods
  272.          */
  273.         @Override
  274.         public void onConnectionFailed(ConnectionResult result) {
  275. //      Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
  276. //              + result.getErrorCode());
  277.         }
  278.  
  279.         @Override
  280.         public void onConnected(Bundle arg0) {
  281.  
  282.             // Once connected with google api, get the location
  283.             displayLocation();
  284.  
  285.             if (mRequestingLocationUpdates) {
  286.                 startLocationUpdates();
  287.             }
  288.         }
  289.  
  290.         @Override
  291.         public void onConnectionSuspended(int arg0) {
  292.             mGoogleApiClient.connect();
  293.         }
  294.  
  295.         /**
  296.          * Starting the location updates
  297.          * */
  298.         protected void startLocationUpdates() {
  299.             try {
  300.                 LocationServices.FusedLocationApi.requestLocationUpdates(
  301.                         mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) getApplicationContext());
  302.             }
  303.             catch (Exception e){
  304.  
  305. //          Log.i("GoogleApi Clien", "" + e);
  306.             }
  307.  
  308.         }
  309.  
  310.         /**
  311.          * Stopping location updates
  312.          */
  313.         protected void stopLocationUpdates() {
  314.             try {
  315.                 LocationServices.FusedLocationApi.removeLocationUpdates(
  316.                         mGoogleApiClient, (com.google.android.gms.location.LocationListener) getApplicationContext());
  317.             }
  318.             catch (Exception e){
  319.  
  320. //          Log.e("GoogleAPI Client",""+e);
  321.  
  322.             }
  323.         }
  324.  
  325.         /**
  326.          * Method to display the location on UI
  327.          * */
  328.         private void displayLocation() {
  329.  
  330.             mLastLocation = LocationServices.FusedLocationApi
  331.                     .getLastLocation(mGoogleApiClient);
  332.  
  333.         }
  334.  
  335.         /**
  336.          * Creating google api client object
  337.          * */
  338.         protected synchronized void buildGoogleApiClient() {
  339.             mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
  340.                     .addConnectionCallbacks(this)
  341.                     .addOnConnectionFailedListener(this)
  342.                     .addApi(LocationServices.API).build();
  343.         }
  344.  
  345.         /**
  346.          * Creating location request object
  347.          * */
  348.         protected void createLocationRequest() {
  349.  
  350.             mLocationRequest = new LocationRequest();
  351.             mLocationRequest.setInterval(UPDATE_INTERVAL);
  352.             mLocationRequest.setFastestInterval(FATEST_INTERVAL);
  353.             mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  354.             mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
  355.         }
  356.         public void stopUpdateLocation(){
  357.             stopLocationUpdates();
  358.         }
  359.         private void makeJsonPostRequest() {
  360.             StringRequest stringRequest = new StringRequest(Request.Method.POST, locationUpdationURL,
  361.                     new Response.Listener<String>() {
  362.                         @Override
  363.                         public void onResponse(String response) {
  364. //                            Log.e("Volley response",response);
  365.                         }
  366.                     },
  367.                     new Response.ErrorListener() {
  368.                         @Override
  369.                         public void onErrorResponse(VolleyError error) {
  370.                         }
  371.                     });
  372.             RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
  373.             requestQueue.add(stringRequest);
  374.         }
  375.     }
  376.     //It will return the value of the ridestart boolean
  377.     private boolean get_ride_status() {
  378.         // TODO Auto-generated method stub
  379.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
  380.         boolean ridestart = ride_info.getBoolean("ride", false);
  381.         return ridestart;
  382.     }
  383.  
  384.     public void set_TravelDistance(double travelDis){
  385.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
  386.         SharedPreferences.Editor editor = ride_info.edit();
  387.         editor.putString("TravelDistance", "" + travelDis);
  388.         editor.commit();
  389.  
  390.     }
  391.  
  392.     private String get_DriverID() {
  393.         // TODO Auto-generated method stub
  394.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
  395.         String d_ID = ride_info.getString("DriverID", "");
  396.         return d_ID;
  397.     }
  398.  
  399.     private String get_TravelDistance() {
  400.         // TODO Auto-generated method stub
  401.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
  402.         String travelDis = ride_info.getString("TravelDistance", "");
  403.         return travelDis;
  404.     }
  405.  
  406.     public void set_LastLocationLatitude(long locLatitude){
  407.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  408.         SharedPreferences.Editor editor = ride_info.edit();
  409.         editor.putLong("LastLocationLatitude", locLatitude);
  410.         editor.commit();
  411.     }
  412.  
  413.     public void set_LastLocationLongitude(long locLatitude){
  414.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  415.         SharedPreferences.Editor editor = ride_info.edit();
  416.         editor.putLong("LastLocationLongitude", locLatitude);
  417.         editor.commit();
  418.     }
  419.  
  420.     private long get_LastLocationLatitude() {
  421.         // TODO Auto-generated method stub
  422.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
  423.         long lat = ride_info.getLong("LastLocationLatitude", 0);
  424.         return lat;
  425.     }
  426.  
  427.     private long get_LastLocationLongitude() {
  428.         // TODO Auto-generated method stub
  429.         SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
  430.         long longi = ride_info.getLong("LastLocationLongitude", 0);
  431.         return longi;
  432.     }
  433. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement