Java 如何解决工作经理';s的定期工作请求行为(类似于UniqueWorkRequest)

Java 如何解决工作经理';s的定期工作请求行为(类似于UniqueWorkRequest),java,android,android-workmanager,periodic-task,Java,Android,Android Workmanager,Periodic Task,我使用PeriodicWorkRequest发送通知(目标是每天一个),但测试是每15分钟一次 通知可以通过应用程序内部的幻灯片激活 这是我的问题: 当我滑动以激活通知时,我会自动收到通知,但如果我将手机时间更改为+1小时 我没有收到新的通知 这是一个基于《纽约时报》API的新闻应用程序。通知基于以下内容: 使用用户在激活通知之前选择的关键字执行搜索APi请求 如果有响应,每天发送一次通知 如果没有回应,不要发送任何东西 举个例子,当我想收到关于“特朗普”关键字和政治复选框的通知时,日志告诉

我使用
PeriodicWorkRequest
发送通知(目标是每天一个),但测试是每15分钟一次 通知可以通过应用程序内部的幻灯片激活

这是我的问题: 当我滑动以激活通知时,我会自动收到通知,但如果我将手机时间更改为+1小时 我没有收到新的通知

这是一个基于《纽约时报》API的新闻应用程序。通知基于以下内容:

  • 使用用户在激活通知之前选择的关键字执行搜索APi请求
  • 如果有响应,每天发送一次通知
  • 如果没有回应,不要发送任何东西
举个例子,当我想收到关于“特朗普”关键字和政治复选框的通知时,日志告诉我他们有200个响应,我只收到一次通知

通知活动:

 /**
 * Set listener to switch to enable notifications
 */
private void initNotification() {
    //Open the keyboard automatically
    search_query.setSelection(0);
    Objects.requireNonNull(this.getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    //Set Listener to switch
    switchNotification.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                //Get user input
                preferences.getUserInput(search_query, null, null,
                        artsCheckBox, businessCheckBox, entrepreneursCheckBox,
                        politicsCheckBox, sportsCheckBox, travelCheckBox);

                //If at least 1 checkbox is selected and user has put one search query --> enable notifications
                if(preferences.checkConditions()) {
                    saveNotificationUrlAndState();
                    enableNotification();
                } else {
                    preferences.clearInput();
                    Toast.makeText(getApplicationContext(), "Please select at least a theme and a keyword", Toast.LENGTH_SHORT).show();
                    switchNotification.toggle();
                }
            }
            //If switch is unchecked
            else {
                cancelNotification();
            }
        }
    });
}

/**
 * Get the user input and save it in SharedPreferences
 */
private void saveNotificationUrlAndState() {
    //Switch button
    preferences.putBoolean(PREF_KEY_SWITCH, true);
    //Edit hint text Text Query
    preferences.putString(PREF_KEY_QUERY, search_query.getText().toString());
    //CheckBoxes
    preferences.putBoolean(PREF_KEY_ARTS, artsCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_POLITICS, politicsCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_BUSINESS, businessCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_ENTREPRENEURS, entrepreneursCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_SPORTS, sportsCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_TRAVEL, travelCheckBox.isChecked());

    //Save search url
    preferences.createSearchUrlForAPIRequest();
    preferences.saveUrl(PREF_KEY_NOTIFICATION_URL);
}

/**
 * Use work manager to run a notification
 */
private void enableNotification(){
    NotificationWorker.scheduleReminder(Constants.TAG_WORKER);
}

/**
 * Cancel notification switch
 */
private void cancelNotification(){
    preferences.clearInput();
    preferences.putBoolean(PREF_KEY_SWITCH, false);

    NotificationWorker.cancelReminder(TAG_WORKER);

    Toast.makeText(NotificationActivity.this, "Notification disabled", Toast.LENGTH_SHORT).show();
}
 @NonNull
@Override
public Result doWork() {

    //Instantiate preferences
    preferences = new SharedPreferencesManager(getApplicationContext());
    //Do request
    doNotificationApiRequest();
    //Send related message
    sendNotification();
    return Result.success();
}


private void doNotificationApiRequest() {
    //Get URL from Notification Activity
    String url = preferences.getString(PREF_KEY_NOTIFICATION_URL);

    //Do API request
    disposable = NYTStreams.streamFetchUrl(url).subscribeWith(new DisposableObserver<NewsObject>() {

        @Override
        public void onNext(NewsObject news) {
            hits = news.checkIfResult();
            message = makeCorrectNotificationMessage(hits);
            preferences.putString(PREF_KEY_NOTIFICATION_MESSAGE, message);
            Logger.i(hits + "");
            Logger.e(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE) + "MESSAGE");

        }

        @Override
        public void onError(Throwable e) {
            //Create notification with error message
            hits = -1;
            message = makeCorrectNotificationMessage(hits);
            Logger.e(e.getMessage());
        }

        @Override
        public void onComplete() {
            Logger.i("notification api request completed, hits :" + hits);
            Logger.e(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE) + "MESSAGE");

        }
    });

}

public static void scheduleReminder(String tag) {
    PeriodicWorkRequest.Builder notificationWork = new PeriodicWorkRequest.Builder(NotificationWorker.class, 16, TimeUnit.MINUTES);
    PeriodicWorkRequest request = notificationWork.build();

    WorkManager.getInstance().enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.REPLACE , request);
}


public static void cancelReminder(String tag) {
    WorkManager instance = WorkManager.getInstance();
    instance.cancelAllWorkByTag(tag);
}

private String makeCorrectNotificationMessage(int hits){
  if (hits == -1) {
      return "Error";
  } else {
      return "There is some new article(s) that might interest you";
  }

}

private void sendNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getApplicationContext().getResources().getString(R.string.notification_title))
            .setContentText(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE));

    Intent intent = new Intent(getApplicationContext(), MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
    builder.setContentIntent(pendingIntent);

    NotificationManager manager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(ID_WORKER_NOTIFICATION, builder.build());
}
通知工人:

 /**
 * Set listener to switch to enable notifications
 */
private void initNotification() {
    //Open the keyboard automatically
    search_query.setSelection(0);
    Objects.requireNonNull(this.getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    //Set Listener to switch
    switchNotification.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                //Get user input
                preferences.getUserInput(search_query, null, null,
                        artsCheckBox, businessCheckBox, entrepreneursCheckBox,
                        politicsCheckBox, sportsCheckBox, travelCheckBox);

                //If at least 1 checkbox is selected and user has put one search query --> enable notifications
                if(preferences.checkConditions()) {
                    saveNotificationUrlAndState();
                    enableNotification();
                } else {
                    preferences.clearInput();
                    Toast.makeText(getApplicationContext(), "Please select at least a theme and a keyword", Toast.LENGTH_SHORT).show();
                    switchNotification.toggle();
                }
            }
            //If switch is unchecked
            else {
                cancelNotification();
            }
        }
    });
}

/**
 * Get the user input and save it in SharedPreferences
 */
private void saveNotificationUrlAndState() {
    //Switch button
    preferences.putBoolean(PREF_KEY_SWITCH, true);
    //Edit hint text Text Query
    preferences.putString(PREF_KEY_QUERY, search_query.getText().toString());
    //CheckBoxes
    preferences.putBoolean(PREF_KEY_ARTS, artsCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_POLITICS, politicsCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_BUSINESS, businessCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_ENTREPRENEURS, entrepreneursCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_SPORTS, sportsCheckBox.isChecked());
    preferences.putBoolean(PREF_KEY_TRAVEL, travelCheckBox.isChecked());

    //Save search url
    preferences.createSearchUrlForAPIRequest();
    preferences.saveUrl(PREF_KEY_NOTIFICATION_URL);
}

/**
 * Use work manager to run a notification
 */
private void enableNotification(){
    NotificationWorker.scheduleReminder(Constants.TAG_WORKER);
}

/**
 * Cancel notification switch
 */
private void cancelNotification(){
    preferences.clearInput();
    preferences.putBoolean(PREF_KEY_SWITCH, false);

    NotificationWorker.cancelReminder(TAG_WORKER);

    Toast.makeText(NotificationActivity.this, "Notification disabled", Toast.LENGTH_SHORT).show();
}
 @NonNull
@Override
public Result doWork() {

    //Instantiate preferences
    preferences = new SharedPreferencesManager(getApplicationContext());
    //Do request
    doNotificationApiRequest();
    //Send related message
    sendNotification();
    return Result.success();
}


private void doNotificationApiRequest() {
    //Get URL from Notification Activity
    String url = preferences.getString(PREF_KEY_NOTIFICATION_URL);

    //Do API request
    disposable = NYTStreams.streamFetchUrl(url).subscribeWith(new DisposableObserver<NewsObject>() {

        @Override
        public void onNext(NewsObject news) {
            hits = news.checkIfResult();
            message = makeCorrectNotificationMessage(hits);
            preferences.putString(PREF_KEY_NOTIFICATION_MESSAGE, message);
            Logger.i(hits + "");
            Logger.e(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE) + "MESSAGE");

        }

        @Override
        public void onError(Throwable e) {
            //Create notification with error message
            hits = -1;
            message = makeCorrectNotificationMessage(hits);
            Logger.e(e.getMessage());
        }

        @Override
        public void onComplete() {
            Logger.i("notification api request completed, hits :" + hits);
            Logger.e(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE) + "MESSAGE");

        }
    });

}

public static void scheduleReminder(String tag) {
    PeriodicWorkRequest.Builder notificationWork = new PeriodicWorkRequest.Builder(NotificationWorker.class, 16, TimeUnit.MINUTES);
    PeriodicWorkRequest request = notificationWork.build();

    WorkManager.getInstance().enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.REPLACE , request);
}


public static void cancelReminder(String tag) {
    WorkManager instance = WorkManager.getInstance();
    instance.cancelAllWorkByTag(tag);
}

private String makeCorrectNotificationMessage(int hits){
  if (hits == -1) {
      return "Error";
  } else {
      return "There is some new article(s) that might interest you";
  }

}

private void sendNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getApplicationContext().getResources().getString(R.string.notification_title))
            .setContentText(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE));

    Intent intent = new Intent(getApplicationContext(), MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
    builder.setContentIntent(pendingIntent);

    NotificationManager manager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(ID_WORKER_NOTIFICATION, builder.build());
}
@NonNull
@凌驾
公共成果工作(){
//实例化首选项
首选项=新的SharedReferencesManager(getApplicationContext());
//请求
doNotificationApiRequest();
//发送相关消息
发送通知();
返回Result.success();
}
私人无效通知请求(){
//从通知活动获取URL
字符串url=preferences.getString(PREF\u KEY\u NOTIFICATION\u url);
//执行API请求
disposable=NYTStreams.streamFetchUrl(url.subscribowith)(新的DisposableObserver(){
@凌驾
public void onNext(新闻对象新闻){
hits=news.checkIfResult();
消息=生成更正通知消息(点击次数);
preferences.putString(PREF_KEY_NOTIFICATION_MESSAGE,MESSAGE);
Logger.i(点击+“”);
Logger.e(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE)+“MESSAGE”);
}
@凌驾
公共无效申报人(可丢弃的e){
//创建带有错误消息的通知
点击率=-1;
消息=生成更正通知消息(点击次数);
Logger.e(e.getMessage());
}
@凌驾
未完成的公共空间(){
Logger.i(“通知api请求已完成,点击次数:“+点击次数”);
Logger.e(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE)+“MESSAGE”);
}
});
}
公共静态无效计划提醒(字符串标记){
PeriodicWorkRequest.Builder notificationWork=新的PeriodicWorkRequest.Builder(NotificationWorker.class,16,时间单位.MINUTES);
PeriodicWorkRequest=notificationWork.build();
WorkManager.getInstance().enqueueUniquePeriodicWork(标记,ExistingPeriodicWorkPolicy.REPLACE,请求);
}
公共静态作废取消提醒(字符串标记){
WorkManager实例=WorkManager.getInstance();
实例.cancelAllWorkByTag(标记);
}
私有字符串MakeCorrectionNotificationMessage(int hits){
如果(点击次数==-1){
返回“错误”;
}否则{
return“有一些新文章可能会引起您的兴趣”;
}
}
私有无效发送通知(){
NotificationCompat.Builder=新建NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_启动器)
.setContentTitle(getApplicationContext().getResources().getString(R.string.notification_title))
.setContentText(preferences.getString(PREF_KEY_NOTIFICATION_MESSAGE));
Intent Intent=新的Intent(getApplicationContext(),MainActivity.class);
PendingEvent PendingEvent=PendingEvent.getActivity(getApplicationContext(),0,intent,0);
builder.setContentIntent(挂起内容);
NotificationManager manager=(NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION\u服务);
manager.notify(ID\u WORKER\u NOTIFICATION,builder.build());
}
您可以在此处找到更多代码: