WorkManager 只需要在特定的时间间隔内工作,如何使用工作管理器约束?工作经理示例

Pra*_*ani 3 android location alarmmanager workmanagers android-workmanager

我是第一次与工作经理合作,我已经成功地实施了它。

我每 30 分钟定位一次以跟踪员工。

我在数据库第一次同步时启动了我的工作管理器,但我想在每天晚上停止它。

这是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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Start Worker 的代码:

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

有什么特别的方法可以在每天晚上停止它吗?

您的帮助将不胜感激。

Qui*_*ner 5

您无法在一段时间内停止Workmanager

这是技巧,只需在doWork()方法中添加此条件

基本上,您需要检查当前时间,即是晚上还是晚上,如果是,请不要执行您的任务。

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案的主要问题是您将运行 doWork() 方法,即使它不是必需的。更好的解决方案是检查 doWork() 中的时间,如果它超出您想要的范围,您可以安排一个具有初始延迟的新 PeriodicWorkRequest(为此您需要 v2.1-alpha02)并返回失败。WorkManager 将负责取消当前的 WorkRequest,当您设置的延迟到期时,您的 Worker 将在下次执行。 (3认同)