Search code examples
androidlocationalarmmanagerandroid-workmanagerworkmanagers

WorkManager need to work only in between particular time interval, how to use work manager constraints ? Work manager example


I am first time working with Work Manager and I have implemented it successfully.

I am taking location on every 30 Minutes to track employee.

I have started my Work Manager when Database synced first time, but I want to stop it on every day by evening.

Here is MyWorker.java

public class MyWorker extends Worker {

    private static final String TAG = "MyWorker";
    /**
     * The desired interval for location updates. Inexact. Updates may be more or less frequent.
     */
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
    /**
     * The fastest rate for active location updates. Updates will never be more frequent
     * than this value.
     */
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    /**
     * The current location.
     */
    private Location mLocation;
    /**
     * Provides access to the Fused Location Provider API.
     */
    private FusedLocationProviderClient mFusedLocationClient;

    private Context mContext;

    private String fromRegRegCode, fromRegMobile, fromRegGUID, fromRegImei, clientIP;

    /**
     * Callback for changes in location.
     */
    private LocationCallback mLocationCallback;

    public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        mContext = context;
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "doWork: Done");
        //mContext.startService(new Intent(mContext, LocationUpdatesService.class));
        Log.d(TAG, "onStartJob: STARTING JOB..");
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
            }
        };

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

        try {
            mFusedLocationClient
                    .getLastLocation()
                    .addOnCompleteListener(new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            if (task.isSuccessful() && task.getResult() != null) {
                                mLocation = task.getResult();

                                String currentTime = CommonUses.getDateToStoreInLocation();
                                String mLatitude = String.valueOf(mLocation.getLatitude());
                                String mLongitude = String.valueOf(mLocation.getLongitude());

                                LocationHistoryTable table = new LocationHistoryTable();
                                table.setLatitude(mLatitude);
                                table.setLongitude(mLongitude);
                                table.setUpdateTime(currentTime);
                                table.setIsUploaded(CommonUses.PENDING);

                                LocationHistoryTableDao tableDao = SohamApplication.daoSession.getLocationHistoryTableDao();
                                tableDao.insert(table);

                                Log.d(TAG, "Location : " + mLocation);
                                mFusedLocationClient.removeLocationUpdates(mLocationCallback);

                                /**
                                 * Upload on server if network available
                                 */
                                if (Util.isNetworkAvailable(mContext)) {
                                    checkForServerIsUP();
                                }

                            } else {
                                Log.w(TAG, "Failed to get location.");
                            }
                        }
                    });
        } catch (SecurityException unlikely) {
            Log.e(TAG, "Lost location permission." + unlikely);
        }

        try {
            mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                    null);
        } catch (SecurityException unlikely) {
            //Utils.setRequestingLocationUpdates(this, false);
            Log.e(TAG, "Lost location permission. Could not request updates. " + unlikely);
        }
        return Result.success();
    }
}

Code for Start Worker:

PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, repeatInterval, TimeUnit.MINUTES)
            .addTag("Location")
            .build();
WorkManager.getInstance().enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);

Is there any particular way to stop it on every day evening?

Your help would be appreciated.


Solution

  • You cannot stop the Workmanager for some period of time.

    Here is the trick just add this condition in doWork() method

    Basically you need to check the current time ie is it evening or night if yes dont perform your task.

    Calendar c = Calendar.getInstance();
    int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
     if(timeOfDay >= 16 && timeOfDay < 21){
        // this condition for evening time and call return here
         return Result.success();
    }
    else if(timeOfDay >= 21 && timeOfDay < 24){
        // this condition for night time and return success 
          return Result.success();
    }