如何使线程在两种方法之间等待

时间:2019-03-17 17:49:38

标签: android database multithreading android-room

我具有此功能-将数据插入android应用中的Room数据库:

public void insertInfoToDB(){

final Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {

            int medId = db.medicationsDao().getMedicationIdByName(medName);

            //insert data to medications table
            MedicationsTable medication = new MedicationsTable(medId, medName, amountDosageMg, remindersAmountPerDay);
            db.medicationsDao().insert(medication);

            //insert data to reminders table
            RemindersTable reminder;
            for (int i = 0; i < selectedDaysSet.size(); i++) {
                for (int j = 0; j < allReminderTimes.size(); j++) {
                    reminder = new RemindersTable(allReminderTimes.get(j).getHour(),
                            allReminderTimes.get(j).getMinutes(), allReminderTimes.get(j).getDoses()
                            , selectedDaysSet.get(i), medication.getId());
                    db.medicationsDao().insertReminder(reminder);

                    createNotification(reminder.getId(), allReminderTimes.get(j).getHour(),
                            allReminderTimes.get(j).getMinutes(), allReminderTimes.get(j).getDoses(),
                            selectedDaysSet.get(i));
                }
            }

将数据插入db时,主键(autoGenerated)的ID为0,我需要在此之后立即使用该键进行操作。 因此,我需要“保留”或“ db.medicationsDao()。insertReminder(reminder);”之间的某个内容。和“ createNotification”(紧随其后),以便线程在我调用createNotification之前完成对数据库的插入。 感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用 CountDownTimer 类:

long waitingTime = 5000; //in milli second
long countDownInteval = 2000;
    CountDownTimer countDownTimer = new CountDownTimer(waitingTime, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            //Write your code here
        }
    };
    countDownTimer.start();

在此代码中,

  • onTick(长期保留)方法将在每2秒后调用一次
  • onFinish()方法将在5秒钟后调用

文档:CountDownTimer