6

I have successfully created an activity with FusedLocationProviderClient that returns location coordinates within a specific period of time.

But I want it to run in background service that saves coordinates in local database and never ends until user stops the service manually.

This is my source code:

private String mLastUpdateTime;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
private static final int REQUEST_CHECK_SETTINGS = 100;
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;

private void init() {
    mFusedLocationClient = 
   LocationServices.getFusedLocationProviderClient(this);
    mSettingsClient = LocationServices.getSettingsClient(this);

    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            // location is received
            mCurrentLocation = locationResult.getLastLocation();
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());

            updateUIAndMarker();
        }
    };

    mRequestingLocationUpdates = false;

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);
    mLocationSettingsRequest = builder.build();
}
Jackson
  • 5,627
  • 2
  • 29
  • 48
Muhammad
  • 127
  • 1
  • 2
  • 13
  • Do you want to use service or workmanager? For your situation, work manager will be the best solution. Give it to a try. – Al-Amin Nov 12 '18 at 08:15
  • Its optional to use service or work manager, It would be great if you share some code or link that run in background until I manually stops. It must be using fusedlocation provider client. Thank you – Muhammad Nov 12 '18 at 09:02
  • Added your solution in my answer please take a look. @Global tech – Al-Amin Nov 12 '18 at 09:04

0 Answers0