WorkManager仅需要在特定时间间隔之间工作

时间:2019-05-24 05:45:43

标签: android android-workmanager

我是第一次与Work Manager合作,并且已经成功实施。

我每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();
    }
}

Start Worker的代码:

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

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

您的帮助将不胜感激。

5 个答案:

答案 0 :(得分:2)

您不能暂停PeriodicWorkRequest,唯一的选择是您必须取消请求。

解决方案:最好在 dowork()方法中添加条件检查,确定当前系统时间是否在下午6点至凌晨6点之间。不执行任何其他操作,您必须添加条件检查。

或您可以使用警报管理器在指定的时间启动服务,然后以指定的时间间隔重复警报。警报响起时,您可以启动服务并连接到服务器并进行所需的操作

答案 1 :(得分:1)

您不能在一段时间内停止 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();
}

答案 2 :(得分:0)

如果您想在特定时间执行某项操作,可以使用AlarmManager像这样:

Intent alaramIntent = new Intent(LoginActivity.this, AutoLogoutIntentReceiver.class);
    alaramIntent.setAction("LogOutAction");
    Log.e("MethodCall","AutoLogOutCall");
    alaramIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alaramIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 18);
    calendar.set(Calendar.MINUTE, 01);
    calendar.set(Calendar.SECOND, 0);
    AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);

    Log.e("Logout", "Auto Logout set at..!" + calendar.getTime());
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

创建一个BroadcastReceiver类:

public class AutoLogoutIntentReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent)
    {

        if("LogOutAction".equals(intent.getAction())){

            Log.e("LogOutAuto", intent.getAction());


            //Stops the visit tracking service
            Intent stopIntent = new Intent(context, VisitTrackingService.class);
            stopIntent.setAction(VisitTrackingService.ACTION_STOP_FOREGROUND_SERVICE);
            context.startService(stopIntent);

            //logs user out of the app and closes it
            SharedPrefManager.getInstance(context).logout();
            exit(context);

        }
    }

并且不要忘记在清单(应用程序标记内)中添加接收方:

<receiver android:name=".AutoLogoutIntentReceiver" />

有关警报管理器的更多信息,请检查此link

希望这会有所帮助!

答案 3 :(得分:0)

我要用两个工人。首先进行管理,其次获得位置。首先是定期工作-晚上每24小时工作一次。它将停止LocationService并延迟再次调用它。

答案 4 :(得分:0)

您可以每天早上启动OneTimeRequest工作线程,这将触发您的PeriodicWorkRequest进行位置收集。并添加时间检查

 //Set initial delay for next OneTimeRequest in DoWork() method which can be calculated as
 public static int initialDelay(){
        int initialDelayMinutes = 0;
        try {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

            Calendar currentDate = Calendar.getInstance();
            Calendar dueDate = Calendar.getInstance();

            // Set Execution around 09:00:00 AM
           dueDate.set(Calendar.DAY_OF_MONTH,currentDate.get(Calendar.DAY_OF_MONTH));
            dueDate.set(Calendar.MONTH,currentDate.get(Calendar.MONTH));
            dueDate.set(Calendar.YEAR,currentDate.get(Calendar.YEAR));
            dueDate.set(Calendar.HOUR_OF_DAY, ChannelierConstants.AUTO_SYNC_TIMING.DAY_START.getType());
            dueDate.set(Calendar.MINUTE, 0);
            dueDate.set(Calendar.SECOND, 0);

            int currentDateHour = currentDate.get(Calendar.HOUR_OF_DAY);
            int dueDateHour = dueDate.get(Calendar.HOUR_OF_DAY);
            int currentDateMinutes = currentDate.get(Calendar.MINUTE);

            //MyUtils.createLog("DUE HOUR "+dueDateHour,"CURRENT HOuR "+currentDateHour+"\t current minutes is "+currentDateMinutes);
            int diff = Math.abs(dueDateHour - currentDateHour);

            //MyUtils.createLog("HOUR DIFF --  "+diff,"24-diff is "+Math.abs(24 - diff));
            if (dueDate.before(currentDate)) {
                currentDate.add(Calendar.HOUR_OF_DAY, Math.abs(24-diff));
                initialDelayMinutes = ((Math.abs(24 - diff)) * 60) +currentDateMinutes;
            }else {
                initialDelayMinutes = 60 - currentDateMinutes;
            }


            createLog("MINUTES "+initialDelayMinutes,"DUE DATE +"+simpleDateFormat.format(currentDate.getTimeInMillis()));

        }catch (Exception ex){
            ex.printStackTrace();
        }
        return initialDelayMinutes;
    }


还要检查periodicWorkRequest的状态,并在未计划/在OneTimeRequest doWork()中运行的情况下触发

最后但并非最不重要的一点是,在PeriodicWorkRequest中检查当前时间,如果超过了结束位置跟踪工作的期望时间,则取消工作

  /**
     * This method is used to cancel periodic autosync if current time is before/ after the mentioned sync time
     * */
    public static boolean shouldCancelPeriodicAutoSync(String wrokerTAG,Context context) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int HOUR_OF_DAY = calendar.get(Calendar.HOUR_OF_DAY);
        createLog("HOUR OF DAY","--> "+HOUR_OF_DAY);
        if (HOUR_OF_DAY > ChannelierConstants.AUTO_SYNC_TIMING.DAY_START.getType() && HOUR_OF_DAY < ChannelierConstants.AUTO_SYNC_TIMING.DAY_END.getType()){
            return true;
        }else {
            createLog("Cancelling Periodic Sync ",""+wrokerTAG);
            WorkManager.getInstance(context).cancelUniqueWork(wrokerTAG);
            return false;
        }
    }