3

我有一个场景,我必须在特定时间使用 WorkManager 给用户通知。

我如何在特定时间安排工作,即使用户强制终止应用程序,它也应该显示出来。或应用程序未运行。

我当前的代码如下:

Data d = new Data.Builder().putInt(IntentConstants.SCHEDULE_ID, scheduleData.getScheduleID()).build();
OneTimeWorkRequest compressionWork =
    new OneTimeWorkRequest.Builder(ScheduleWorker.class)
        .setInputData(d)
        .build();
WorkManager.getInstance().enqueue(compressionWork);
4

3 回答 3

6

我想我找到了一个简单有效的解决方案。它可以 100% 工作。

我们必须以毫秒为单位获取当前时间,并以毫秒为单位触发它所需的特定时间,然后您必须计算特定时间 - 当前时间。

我有我的解决方案(下面的工作代码):

Data d = new Data.Builder()
             .putInt(IntentConstants.SCHEDULE_ID, scheduleData.getScheduleID())
             .build();

long currentTime= System.currentTimeMillis();
long specificTimeToTrigger = c.getTimeInMillis();
long delayToPass = specificTimeToTrigger - currentTime;

OneTimeWorkRequest compressionWork =
                        new OneTimeWorkRequest.Builder(ScheduleWorker.class)
                                .setInputData(d)
                                .setInitialDelay(delayToPass, TimeUnit.MILLISECONDS)
                                .build();

WorkManager.getInstance().enqueue(compressionWork);

主要逻辑在delayToPass = currentTime (in Millis) - specificTimeToTrigger (in Millis)

于 2018-08-05T14:00:38.120 回答
0
long currentTime= System.currentTimeMillis();
long specificTimeToTrigger = c.getTimeInMillis();
long delayToPass = specificTimeToTrigger - currentTime;

OneTimeWorkRequest compressionWork =
                        new OneTimeWorkRequest.Builder(ScheduleWorker.class)
                                .setInitialDelay(delayToPass, TimeUnit.MILLISECONDS)
                                .build();

WorkManager.getInstance().enqueue(compressionWork);

It's trigger correct on selected time when selected time > current time. 如果选择的时间<当前时间,它会立即触发。

为了克服立即触发,如果所选时间小于当前时间,您可以使用以下条件在第二天触发。

if ((specificTimeToTrigger - currentTime) < 0) {
    delayToPass = (86400000)-(currentTime - specificTimeToTrigger);
    //24hr-(currentTime - specificTimeToTrigger)
} else {
    delayToPass = specificTimeToTrigger - currentTime;
}
于 2021-07-05T13:26:05.943 回答
-1

接受的答案是准确的,但我认为有一个小细节会误导
delayToPass = currentTime (in Millis) - specificTimeToTrigger (in Millis) 这在我看来是行不通的,它应该是:
delayToPass = specificTimeToTrigger (in Millis)-currentTime (in Millis)

于 2020-08-08T13:36:25.787 回答