Agregar un elemento a RecyclerView a una hora específica todos los días

Micheal_ Moris:

Necesito código para añadir el artículo a RecyclerViewlas 12 de la mañana cada día. He intentado muchas formas, como gestor de trabajo y gerente de alarma pero no lograr este objetivo

Nicolas:

Aquí está una implementación de lo que he mencionado en mi comentario:

public class MainActivity extends AppCompatActivity {
    private static final String PREF_PAUSE_TIME_KEY = "exit_time";

    private static final Long MILLIS_IN_DAY = 86400000L;

    private static final int TRIGGER_HOUR = 12;
    private static final int TRIGGER_MIN = 0;
    private static final int TRIGGER_SEC = 0;

    private final Handler handler = new Handler();
    private SharedPreferences prefs;

    private final Calendar calendar = Calendar.getInstance();

    private final Runnable addItemRunnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(addItemRunnable, MILLIS_IN_DAY);
            addItem();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Add missing events since onPause.
        long resumeTime = System.currentTimeMillis();
        long pauseTime = prefs.getLong(PREF_PAUSE_TIME_KEY, resumeTime);

        // Set calendar to trigger time on the day the app was paused.
        calendar.setTimeInMillis(pauseTime);
        calendar.set(Calendar.HOUR_OF_DAY, TRIGGER_HOUR);
        calendar.set(Calendar.MINUTE, TRIGGER_MIN);
        calendar.set(Calendar.SECOND, TRIGGER_SEC);

        long time;
        while (true) {
            // If calendar time is during the time that app was on pause, add item.
            time = calendar.getTimeInMillis();
            if (time > resumeTime) {
                // Past current time, all items were added.
                break;
            } else if (time >= pauseTime) {
                // This time happened when app was on pause, add item.
                addItem();
            }

            // Set calendar time to same hour on next day.
            calendar.add(Calendar.DATE, 1);
        }

        // Set handler to add item on trigger time.
        handler.postDelayed(addItemRunnable, time - resumeTime);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // Save pause time so items can be added on resume.
        prefs.edit().putLong(PREF_PAUSE_TIME_KEY, System.currentTimeMillis()).apply();

        // Cancel handler callback to add item.
        handler.removeCallbacks(addItemRunnable);
    }

    private void addItem() {
        // Add item to database and RecyclerView.
    }
}
  • Cuando onPausese llama, la hora actual se guarda en las preferencias.
  • Cuando onResumese llama, el programa de añadir todos los elementos que se deberían haber añadido, mientras que no se abrió la aplicación.
  • Cuando se abre la aplicación del programa utiliza una Handlerpara publicar una tarea en un momento específico.

Se puede mover el código que desee en cualquier lugar, muy probablemente en su repositorio o ver modelo si usted tiene uno. Para el temporizador se puede utilizar para el temporizador RxJava dentro de la aplicación o cualquier otra cosa en realidad.

Si el usuario cambia el tiempo para un par de días anteriores, no se eliminarán los puntos añadidos. Si el usuario se establece a continuación, volver a la normalidad, se duplicarán artículos para algunos días. Esto se puede evitar solamente el ahorro de tiempo en onPausesi es mayor que la última vez guardado.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=359856&siteId=1
Recomendado
Clasificación