Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.apps.taxi.iridedriverapp.Services;
- import android.app.Service;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.os.PowerManager;
- import android.preference.PreferenceManager;
- import android.util.Log;
- import android.widget.Toast;
- import com.android.volley.Request;
- import com.android.volley.RequestQueue;
- import com.android.volley.Response;
- import com.android.volley.VolleyError;
- import com.android.volley.VolleyLog;
- import com.android.volley.toolbox.JsonObjectRequest;
- import com.android.volley.toolbox.StringRequest;
- import com.android.volley.toolbox.Volley;
- import com.apps.taxi.iridedriverapp.config.AppsDriverApplication;
- import com.apps.taxi.iridedriverapp.models.DRIVER;
- import com.apps.taxi.iridedriverapp.models.History;
- import com.apps.taxi.iridedriverapp.serviceHandler.GPSTracker;
- import com.apps.taxi.iridedriverapp.utils.Utills;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.GooglePlayServicesUtil;
- import com.google.android.gms.common.api.GoogleApiClient;
- import com.google.android.gms.location.LocationRequest;
- import com.google.android.gms.location.LocationServices;
- import org.json.JSONException;
- import org.json.JSONObject;
- /**
- * Created by ARBI on 23/02/2016.
- */
- public class LocationServicess extends Service
- {
- public static final String BROADCAST_ACTION = "Hello World";
- private static final int TWO_MINUTES = 1000;
- public LocationManager locationManager;
- public MyLocationListener listener;
- public Location previousBestLocation = null;
- GPSTracker gpsTracker;
- Intent intent;
- int counter = 0;
- double travelDistance=0;
- String locationUpdationURL="";
- Location LastLocation;
- Location newLocation;
- Location mLastLocation;
- // Fused Apis
- private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
- // Google client to interact with Google API
- private GoogleApiClient mGoogleApiClient;
- // boolean flag to toggle periodic location updates
- private boolean mRequestingLocationUpdates = false;
- private LocationRequest mLocationRequest;
- // Location updates intervals in sec
- private static int UPDATE_INTERVAL = 10000; // 20 sec
- private static int FATEST_INTERVAL = 10000; // 20 sec
- private static int DISPLACEMENT = 10; // 10 meters
- PowerManager powerManager;
- PowerManager.WakeLock wakeLock;
- @Override
- public void onCreate()
- {
- super.onCreate();
- gpsTracker = new GPSTracker(this);
- intent = new Intent(BROADCAST_ACTION);
- if(!get_TravelDistance().equals("")){
- travelDistance=Double.parseDouble(get_TravelDistance());
- }
- powerManager = (PowerManager) getSystemService(POWER_SERVICE);
- wakeLock= powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
- "MyWakelockTag");
- wakeLock.acquire();
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- listener = new MyLocationListener();
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, listener);
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, listener);
- if(gpsTracker.getLocation()!=null && get_ride_status()) {
- LastLocation = gpsTracker.getLocation();
- newLocation = gpsTracker.getLocation();
- }
- if(!get_TravelDistance().equals("")){
- travelDistance=Double.parseDouble(get_TravelDistance());
- }
- // return START_STICKY;
- return super.onStartCommand(intent, flags, startId);
- }
- @Override
- public IBinder onBind(Intent intent)
- {
- return null;
- }
- protected boolean isBetterLocation(Location location, Location currentBestLocation) {
- if (currentBestLocation == null) {
- // A new location is always better than no location
- return true;
- }
- // Check whether the new location fix is newer or older
- long timeDelta = location.getTime() - currentBestLocation.getTime();
- boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
- boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
- boolean isNewer = timeDelta > 0;
- // If it's been more than two minutes since the current location, use the new location
- // because the user has likely moved
- if (isSignificantlyNewer) {
- return true;
- // If the new location is more than two minutes older, it must be worse
- } else if (isSignificantlyOlder) {
- return false;
- }
- // Check whether the new location fix is more or less accurate
- int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
- boolean isLessAccurate = accuracyDelta > 5;
- boolean isMoreAccurate = accuracyDelta < 5;
- boolean isSignificantlyLessAccurate = accuracyDelta > 200;
- // Check if the old and new location are from the same provider
- boolean isFromSameProvider = isSameProvider(location.getProvider(),
- currentBestLocation.getProvider());
- // Determine location quality using a combination of timeliness and accuracy
- if (isMoreAccurate) {
- return true;
- } else if (isNewer && !isLessAccurate) {
- return true;
- } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
- return true;
- }
- return false;
- }
- /** Checks whether two providers are the same */
- private boolean isSameProvider(String provider1, String provider2) {
- if (provider1 == null) {
- return provider2 == null;
- }
- return provider1.equals(provider2);
- }
- @Override
- public void onDestroy() {
- // handler.removeCallbacks(sendUpdatesToUI);
- super.onDestroy();
- listener.stopUpdateLocation();
- Log.v("STOP_SERVICE", "DONE");
- locationManager.removeUpdates(listener);
- wakeLock.release();
- }
- public static Thread performOnBackgroundThread(final Runnable runnable) {
- final Thread t = new Thread() {
- @Override
- public void run() {
- try {
- runnable.run();
- } finally {
- }
- }
- };
- t.start();
- return t;
- }
- public class MyLocationListener implements LocationListener,GoogleApiClient.ConnectionCallbacks,
- GoogleApiClient.OnConnectionFailedListener {
- public MyLocationListener(){
- buildGoogleApiClient();
- createLocationRequest();
- if (mGoogleApiClient != null) {
- mGoogleApiClient.connect();
- }
- displayLocation();
- }
- public void onLocationChanged(final Location loc) {
- Log.i("******", "Location changed");
- mLastLocation=loc;
- if (loc != null &&newLocation!=null&&LastLocation!=null) {
- newLocation.setLatitude(loc.getLatitude());
- newLocation.setLongitude(loc.getLongitude());
- if ( get_ride_status() && LastLocation.getLatitude() != loc.getLatitude() && LastLocation.getLongitude() != loc.getLongitude()) {
- double newDistance = LastLocation.distanceTo(loc);
- Log.e("newDistance-------",""+newDistance);
- int suitableMeter = 20;
- if (loc.getAccuracy() <= suitableMeter) {
- LastLocation = loc;
- set_LastLocationLongitude((long)loc.getLongitude());
- set_LastLocationLatitude((long)loc.getLatitude());
- newDistance = newDistance / 900;
- Log.e("newDistance/////////",""+newDistance);
- travelDistance = travelDistance + newDistance;
- // Toast.makeText(getApplicationContext(), "" + travelDistance + " KM", Toast.LENGTH_SHORT).show();
- set_TravelDistance(travelDistance);
- }
- loc.getLatitude();
- loc.getLongitude();
- intent.putExtra("Latitude", loc.getLatitude());
- intent.putExtra("Longitude", loc.getLongitude());
- intent.putExtra("Provider", loc.getProvider());
- sendBroadcast(intent);
- locationUpdationURL = "http://appstaxi.com/mappservicesia/index.php?command=update_driver_location&" +
- "user_id=" + get_DriverID() + "&" +
- "longitude=" + loc.getLongitude() + "&" +
- "latitude=" + loc.getLatitude() + "&" +
- "distance_travelled=" + get_TravelDistance();
- }
- }
- if(Utills.isOnline(getApplicationContext())) {
- makeJsonPostRequest();
- }
- displayLocation();
- }
- public void onProviderDisabled(String provider)
- {
- // Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
- }
- public void onProviderEnabled(String provider)
- {
- // Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
- }
- public void onStatusChanged(String provider, int status, Bundle extras)
- {
- }
- /**
- * Google api callback methods
- */
- @Override
- public void onConnectionFailed(ConnectionResult result) {
- // Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
- // + result.getErrorCode());
- }
- @Override
- public void onConnected(Bundle arg0) {
- // Once connected with google api, get the location
- displayLocation();
- if (mRequestingLocationUpdates) {
- startLocationUpdates();
- }
- }
- @Override
- public void onConnectionSuspended(int arg0) {
- mGoogleApiClient.connect();
- }
- /**
- * Starting the location updates
- * */
- protected void startLocationUpdates() {
- try {
- LocationServices.FusedLocationApi.requestLocationUpdates(
- mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) getApplicationContext());
- }
- catch (Exception e){
- // Log.i("GoogleApi Clien", "" + e);
- }
- }
- /**
- * Stopping location updates
- */
- protected void stopLocationUpdates() {
- try {
- LocationServices.FusedLocationApi.removeLocationUpdates(
- mGoogleApiClient, (com.google.android.gms.location.LocationListener) getApplicationContext());
- }
- catch (Exception e){
- // Log.e("GoogleAPI Client",""+e);
- }
- }
- /**
- * Method to display the location on UI
- * */
- private void displayLocation() {
- mLastLocation = LocationServices.FusedLocationApi
- .getLastLocation(mGoogleApiClient);
- }
- /**
- * Creating google api client object
- * */
- protected synchronized void buildGoogleApiClient() {
- mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API).build();
- }
- /**
- * Creating location request object
- * */
- protected void createLocationRequest() {
- mLocationRequest = new LocationRequest();
- mLocationRequest.setInterval(UPDATE_INTERVAL);
- mLocationRequest.setFastestInterval(FATEST_INTERVAL);
- mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
- mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
- }
- public void stopUpdateLocation(){
- stopLocationUpdates();
- }
- private void makeJsonPostRequest() {
- StringRequest stringRequest = new StringRequest(Request.Method.POST, locationUpdationURL,
- new Response.Listener<String>() {
- @Override
- public void onResponse(String response) {
- // Log.e("Volley response",response);
- }
- },
- new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- }
- });
- RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
- requestQueue.add(stringRequest);
- }
- }
- //It will return the value of the ridestart boolean
- private boolean get_ride_status() {
- // TODO Auto-generated method stub
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
- boolean ridestart = ride_info.getBoolean("ride", false);
- return ridestart;
- }
- public void set_TravelDistance(double travelDis){
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
- SharedPreferences.Editor editor = ride_info.edit();
- editor.putString("TravelDistance", "" + travelDis);
- editor.commit();
- }
- private String get_DriverID() {
- // TODO Auto-generated method stub
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
- String d_ID = ride_info.getString("DriverID", "");
- return d_ID;
- }
- private String get_TravelDistance() {
- // TODO Auto-generated method stub
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
- String travelDis = ride_info.getString("TravelDistance", "");
- return travelDis;
- }
- public void set_LastLocationLatitude(long locLatitude){
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
- SharedPreferences.Editor editor = ride_info.edit();
- editor.putLong("LastLocationLatitude", locLatitude);
- editor.commit();
- }
- public void set_LastLocationLongitude(long locLatitude){
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
- SharedPreferences.Editor editor = ride_info.edit();
- editor.putLong("LastLocationLongitude", locLatitude);
- editor.commit();
- }
- private long get_LastLocationLatitude() {
- // TODO Auto-generated method stub
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
- long lat = ride_info.getLong("LastLocationLatitude", 0);
- return lat;
- }
- private long get_LastLocationLongitude() {
- // TODO Auto-generated method stub
- SharedPreferences ride_info = PreferenceManager.getDefaultSharedPreferences(this);
- long longi = ride_info.getLong("LastLocationLongitude", 0);
- return longi;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement