gpt4 book ai didi

java - 每天在特定时间将项目添加到房间数据库

转载 作者:行者123 更新时间:2023-12-01 17:43:20 24 4
gpt4 key购买 nike

我需要代码才能每天中午 12 点将项目添加到房间数据库。我尝试了很多方法,例如 WorkManagerAlarmManager 但他们没有实现这个目标

最佳答案

这是我在评论中提到的内容的实现:

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.
}
}
  • 调用 onPause 时,当前时间将保存在首选项中。
  • 调用 onResume 时,程序会添加应用未打开时应添加的所有项目。
  • 当应用打开时,程序会使用Handler 在特定时间发布任务。

您可以将代码移动到任何您想要的位置,最有可能在您的存储库或 View 模型中(如果有的话)。对于计时器,您可以使用 RxJava 作为应用内计时器或其他任何东西。

如果用户将时间更改为提前几天,添加的项目将不会被删除。如果用户随后将其恢复正常,则某些天的项目将会重复。您可以通过仅在 onPause 中保存时间(如果它大于上次保存的时间)来防止这种情况。

关于java - 每天在特定时间将项目添加到房间数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com