Как разрешить поведение периодического рабочего запроса Work Manager (действует как UniqueWorkRequest) - PullRequest
1 голос
/ 09 июля 2019

Я использую PeriodicWorkRequest для отправки уведомлений (цель - один в день), но для тестирования каждые 15 минут Уведомление можно активировать с помощью слайда внутри приложения

Вот моя проблема: Когда я двигаюсь, чтобы активировать уведомление, я автоматически получаю уведомление, но если я изменяю время моего телефона на +1 час, я не получаю новое уведомление

Это приложение новостей, основанное на НовыхAPI york Times. Уведомление основано на следующем:

  • Выполнить поисковый запрос 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

...