0

In the Android app that I am working on.

  • I want to take the user location and send it to the server on a post request every 5 seconds; Even when the app is running in the background
  • I want to send all geolocation info included bearing.
  • I need a method to call to start the sending job and a method to stop the sending job.
  • The plan is to only send the new data as the old ones have already been sent. To avoid overloading data all at once to the server.
TheEhsanSarshar
  • 2,677
  • 22
  • 41
  • Sending something every 5 seconds will quickly drain the battery. Also, you may have difficulties to pass the app review for using location in background. – Henry Jul 06 '20 at 07:46
  • check this https://stackoverflow.com/questions/39953053/how-to-find-my-current-location-latitude-longitude-in-every-5-second-in-andr – Nour Eldien Mohamed Jul 06 '20 at 07:46
  • Check the answer of this [post](https://stackoverflow.com/questions/62695437/issue-in-creating-a-full-time-running-background-service-in-android-app/62695694?noredirect=1#comment110895507_62695694) – leimenghao Jul 06 '20 at 07:48
  • so the thing that remain is that I only want to call for another location request when the current one has already been send to server – TheEhsanSarshar Jul 06 '20 at 07:58
  • @Henry then whats the solution – TheEhsanSarshar Jul 06 '20 at 07:58

1 Answers1

1

you must be writing service and for getting location you use from smartlocation library

public class StatusUserServices extends Service {
public static final String BROADCAST_ACTION = "reporter";
private static final int TWO_SECONDS = 1000 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Intent intent;
int counter = 0;
protected Handler handler;
double lat,longi;
private final LocalBinder mBinder = new LocalBinder();
boolean speed;
public class LocalBinder extends Binder {
    public StatusUserServices getService() {
        return StatusUserServices .this;
    }
}
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
@Override
public void onCreate() {
    super.onCreate();
    intent = new Intent(BROADCAST_ACTION);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();
     if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

     }
    if (locationManager != null){
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if( !isGPSEnabled && !isNetworkEnabled) {

            showGPSDisabledAlertToUser();

        } else {

            if(isGPSEnabled) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2*1000, 100, listener);
            } else if(isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,2*1000,100, listener);
            }
        }
    }




    return START_STICKY;
}



protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        return true;
    }
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;
    if (isSignificantlyNewer) {
        return true;
    } else if (isSignificantlyOlder) {
        return false;
    }
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 3000;
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

private void showGPSDisabledAlertToUser(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage(getResources().getString(R.string.ActivateGPSQuestion))
            .setCancelable(false)
            .setPositiveButton(R.string.GoToTheSettingsPage,
                    (dialog, id) -> {
                        Intent callGPSSettingIntent = new Intent(
                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(callGPSSettingIntent);
                    });
    alertDialogBuilder.setNegativeButton(R.string.cancel,
            (dialog, id) -> dialog.cancel());
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}



@Override
public void onDestroy() {
    super.onDestroy();
    Log.v("STOP_SERVICE", "DONE");
    if (locationManager != null) {
        try {
            locationManager.removeUpdates(listener);
        } catch (Exception ex) {
            Log.i("******", "fail to remove location listners, ignore", ex);
        }

    }
}


public class MyLocationListener implements LocationListener
{

    public void onLocationChanged(final Location loc)
    {

        if(isBetterLocation(loc, previousBestLocation)) {

            SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
            SimpleDateFormat time= new SimpleDateFormat("HH:mm:ss", Locale.US);
            if(loc.getLatitude() == 0.0 && loc.getLongitude() == 0.0){
                SmartLocation.with(getApplicationContext()).location()
                        .start(location -> {
                            lat = location.getLatitude();
                            longi = location.getLongitude();
                            speed = location.hasSpeed();
                        });
            }else{
                lat = loc.getLatitude();
                longi = loc.getLongitude();
                speed = loc.hasSpeed();
            }
            String times = time.format(new Date());
            String dates = date.format(new Date());
            intent.putExtra("Latitude", lat);
            intent.putExtra("Longitude", longi);
            intent.putExtra("Speed", speed);
            intent.putExtra("Time", times);
            intent.putExtra("Date", dates);
            intent.setAction(BROADCAST_ACTION);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
        }
    }


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void onProviderDisabled(String provider)
    {

    }


    public void onProviderEnabled(String provider)
    {

    }
}

}

hosein moradi
  • 444
  • 3
  • 7