Android Send Data To external Server Without Delay using service


public class GPSLocationService extends Service implements LocationListener {
   
float speed=0;
double kmphSpeed;
     // flag for GPS status
    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 10000; // 10 secs
    // Declaring a Location Manager
    protected LocationManager locationManager;
   
    AlarmManager alarmManager;
    PendingIntent pendingIntent;
    WakefulBroadcastReceiver mReceiver;
   
    SharedPreferences mypref;
Editor myeditor;
   
 
int  timer;
String url="http://192.168.1.101/TripTracker/datainsert.php?";
    public int onStartCommand(Intent intent, int flags, int startId){
   mypref = this.getSharedPreferences("Trip", MODE_PRIVATE);
myeditor = mypref.edit();
String timespan=mypref.getString("gpsrefresh", null);
        timer=Integer.parseInt(timespan);
        timer=timer*1000;
     
       
    getLocation();
        RegisterAlarmBroadcast();
        SetTimer();


        Log.w("Service", "Start");
       return START_STICKY;  
 }
    @Override
    public void onDestroy() {
      Log.w("Debug", "Destroy");
      unregisterReceiver(mReceiver);
      alarmManager.cancel(pendingIntent);

    }
   
private  void SendBroadCast(String message)
{
Log.w("call", "call");
Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MessageBroadCast.PROCESS_RESPONSE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("Message", message);
     sendBroadcast(broadcastIntent);


}
   
   
    private void RegisterAlarmBroadcast() {
    // TODO Auto-generated method stub
      mReceiver = new WakefulBroadcastReceiver() {
               // private static final String TAG = "Alarm Example Receiver";
               @Override
               public void onReceive(Context context, Intent intent) {
//                   Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
           
              Log.d("Check", Global.check);
              Log.w("Check", Global.check);
              Log.w("Check", "Check");
             
              if(Global.check.equalsIgnoreCase("a"));
             {
             getLocation();
             Sync();
            Log.w("sync", "autosync");
             }
             if (Global.check.equalsIgnoreCase("b"));
           {
            Log.w("sync", "notautosync");
           }
           
               }
           };

           registerReceiver(mReceiver, new IntentFilter("com.aks.trip"));
           pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.aks.trip"), 0);
           alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));

    }
   
   
   
    public void Sync() {
// TODO Auto-generated method stub
    SimpleDateFormat fdate,ftime,fhours,fmin,fsec;
    Calendar cc = Calendar.getInstance();
    fdate = new SimpleDateFormat("dd/MM/yyyy");
    ftime=new SimpleDateFormat("HH:mm:ss");
    String date = fdate.format(cc.getTime());
        String time =ftime.format(cc.getTime());
        String lati=getLatitude()+"";
        String longi=getLongitude()+"";
        String username=mypref.getString("username", null);
        String imei=mypref.getString("imei", null);
        String serverposturl=mypref.getString("serverposturl", null);
       
        String timespan=mypref.getString("gpsrefresh", null);
        timer=Integer.parseInt(timespan);
        timer=timer*1000;
       
  Log.w("username", username);
Log.w("lati", lati);
Log.w("longi", longi);
Log.w("imei", imei);
Log.w("serverposturl", serverposturl);
Log.w("date", date);
Log.w("time", time);

SendBroadCast("GPS Location Recorded");
String data="http://ykproject.netne.net/TripTracker/datainsert.php?username="+username+"&imei="+imei+"&lat="+lati+"&long="+longi+"&date="+date+"&time="+time;


SyncData(data);
}

    public double round(double value, int places) {
   if (places < 0) throw new IllegalArgumentException();

   long factor = (long) Math.pow(10, places);
   value = value * factor;
   long tmp = Math.round(value);
   return (double) tmp / factor;
}
private void SetTimer() {
    // TODO Auto-generated method stub
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.currentThreadTimeMillis(), timer, pendingIntent);
   
    }
   
    public Location getLocation() {
        try {
            locationManager = (LocationManager) this
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }
 
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSLocationService.this);
        }  
     
    }
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }    
        // return latitude
        return latitude;
    }  
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }      
        // return longitude
        return longitude;
    }  
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }  
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
   

    public double GetSpeeed()
    {
    return kmphSpeed;
    }
   
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onLocationChanged(Location k) {
// TODO Auto-generated method stub
  speed= k.getSpeed();
 double currentSpeed = round(speed,3,BigDecimal.ROUND_HALF_UP);
      kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
}
public static double round(double unrounded, int precision, int roundingMode)
{
    BigDecimal bd = new BigDecimal(unrounded);
    BigDecimal rounded = bd.setScale(precision, roundingMode);
    return rounded.doubleValue();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}

public void SyncData(String JSON_URL){


StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Log.w("response", response);
SendBroadCast("Upload Sucessfully");
  }
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Log.w("error", error.getMessage());
SendBroadCast("Upload Failed");
    }
});

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

}

Comments