如何解决工作管理器的定期工作请求行为(类似于UniqueWorkRequest)

时间:2019-07-09 08:16:10

标签: java android android-workmanager periodic-task

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

激活通知

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

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

  • 使用用户在激活通知之前选择的关键字进行搜索APi请求
  • 如果有回应,则每天发送一次通知
  • 如果没有回应,请不要发送任何邮件

例如,当我想收到有关“王牌”关键字和“政治”复选框的通知时,日志告诉我它们是200〜响应,我只收到一次通知

NotificationActivity:

 /**
 * 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();
}

NotificationWorker:

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

您可以在此处找到更多代码: https://github.com/matteovaccari/MyNews

0 个答案:

没有答案