diff --git a/AlarmInitReceiver.txt b/AlarmInitReceiver.txt new file mode 100644 index 0000000..6c05ad6 --- /dev/null +++ b/AlarmInitReceiver.txt @@ -0,0 +1,52 @@ + +/** + * 闹钟初始化接收器,用于设置便签的闹钟提醒。 + */ +public class AlarmInitReceiver extends BroadcastReceiver { + + // 查询字段 + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, // 便签ID + NoteColumns.ALERTED_DATE // 便签的提醒日期 + }; + + // 查询字段对应的列索引 + private static final int COLUMN_ID = 0; + private static final int COLUMN_ALERTED_DATE = 1; + + /** + * 接收到广播时调用。 + * @param context 上下文对象 + * @param intent 广播时传递的Intent + */ + @Override + public void onReceive(Context context, Intent intent) { + // 获取当前日期 + long currentDate = System.currentTimeMillis(); + // 查询所有未提醒且类型为便签的便签项 + Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, + new String[] { String.valueOf(currentDate) }, + null); + + if (c != null) { + if (c.moveToFirst()) { + // 遍历查询结果,为每个便签设置闹钟 + do { + long alertDate = c.getLong(COLUMN_ALERTED_DATE); + Intent sender = new Intent(context, AlarmReceiver.class); + // 设置闹钟接收器的数据,以便知道是哪个便签需要提醒 + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); + PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); + AlarmManager alermManager = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + // 设置闹钟,使用RTC_WAKEUP模式确保设备在提醒时间被唤醒 + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + } while (c.moveToNext()); + } + c.close(); + } + } +} +