/* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.micode.notes.ui; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; /** * AlarmInitReceiver 类是一个广播接收器,用于在接收到特定广播时, * 初始化所有已设置且未触发的提醒闹钟。 */ public class AlarmInitReceiver extends BroadcastReceiver { // 定义查询笔记时需要的列,包括笔记的 ID 和提醒日期 private static final String [] PROJECTION = new String [] { NoteColumns.ID, NoteColumns.ALERTED_DATE }; // 定义查询结果中笔记 ID 所在的列索引 private static final int COLUMN_ID = 0; // 定义查询结果中提醒日期所在的列索引 private static final int COLUMN_ALERTED_DATE = 1; /** * 当接收到广播时,此方法会被调用。 * 它会查询所有设置了提醒且提醒日期在当前时间之后的笔记, * 并为每个笔记设置一个闹钟。 * * @param context 上下文对象,用于访问系统服务和内容提供者 * @param 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); // 创建一个新的意图,用于触发 AlarmReceiver 广播接收器 Intent sender = new Intent(context, AlarmReceiver.class); // 设置意图的数据,包含笔记的 URI 和 ID sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); // 创建一个 PendingIntent,用于在闹钟触发时发送广播 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(); } } }