带有Room的Android BroadcastReceiver数据库访问

时间:2018-08-30 13:44:19

标签: android broadcastreceiver android-room android-broadcastreceiver android-database

我已经设置了一个闹钟,该闹钟每个小时呼叫广播接收机。该接收器尝试从sqlite数据库加载数据。

问题是,提醒列表为空。相同的代码在活动中有效,但在接收者中无效。有什么我需要更改才能访问接收器中的数据库的吗?这是活动和接收方中不同上下文的问题吗?

“ setAlarm”方法是我用来在活动上创建警报的方法。

致谢

public class AppReceiver extends BroadcastReceiver {

    private static final String TAG = "AppReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        ReminderRepository mRepository; = new ReminderRepository(context);
        List<Reminder> list = mRepository.getAllReminder();
        for(Reminder r : list) {
            // TODO
        }
    }
}


public class ReminderRepository {

    private ReminderDao mReminderDao;
    private List<Reminder> mAllReminder;

    public DisposalCalenderRepository(Context context) {
        ReminderRoomDatabase db = ReminderRoomDatabase.getDatabase(context);
        mReminderDao = db.reminderDao();
        mAllReminder = mReminderDao.getAll();
    }

    public List<Reminder> getAllReminder(){
        return mAllReminder;
    }

}

@Dao
public interface ReminderDao {

    @Query("SELECT * from reminder")
    List<Reminder> getAll();

}

public void setAlarm(){
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.HOUR, 1);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    AlarmManager alarmMgr = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(mContext, AppReceiver.class);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(mContext, 0, i, 0);

    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_HOUR, alarmIntent);
    }

1 个答案:

答案 0 :(得分:2)

我找到了两个可能的答案。

解决方案1:启动异步任务。创建一个AsyncTask类,并在doBackground方法中进行处理。访问数据库没有更多问题。

@Override
public void onReceive(Context context, Intent intent) {
    new notifyAsyncTask().execute(context);
}

private static class notifyAsyncTask extends AsyncTask<Context, Void, Void> {

        private String CHANNEL_ID = "1a2b3c4d";

        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        protected Void doInBackground(Context... params) {
            Log.i(TAG, "Notify async started");
        ReminderRepository mRepository; = new ReminderRepository(context);
        List<Reminder> list = mRepository.getAllReminder();
        for(Reminder r : list) {
                // TODO
        }
    }
}

解决方案2:允许在主线程上查询。构建数据库后,使用allowMainThreadQueries()允许对主线程进行查询。

!!!!注意!!!!不建议 !!!!注意!!!!