/* * 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; /** * 便签提醒初始化接收器 * 用于在系统启动或特定事件触发时,重新注册所有未过期的便签提醒闹钟 * 确保用户设置的便签提醒不会因系统重启等原因丢失 */ public class AlarmInitReceiver extends BroadcastReceiver { /** * 数据库查询字段投影:只查询便签ID和提醒时间 * 优化查询效率,避免获取不必要的字段 */ private static final String [] PROJECTION = new String [] { NoteColumns.ID, // 便签ID NoteColumns.ALERTED_DATE // 提醒时间戳 }; // 字段索引常量,用于快速访问Cursor中的数据 private static final int COLUMN_ID = 0; // 便签ID在投影中的索引 private static final int COLUMN_ALERTED_DATE = 1; // 提醒时间在投影中的索引 /** * 接收广播时触发的回调方法 * 负责查询所有未过期的便签提醒,并重新注册到AlarmManager * @param context 上下文对象 * @param intent 接收到的广播意图 */ @Override public void onReceive(Context context, Intent intent) { // 获取当前系统时间,用于筛选未过期的提醒 long currentDate = System.currentTimeMillis(); // 查询数据库中所有未过期的便签提醒 // 条件:提醒时间 > 当前时间 且 便签类型为普通便签(TYPE_NOTE) Cursor c = context.getContentResolver().query( Notes.CONTENT_NOTE_URI, // 查询的内容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); // 为意图附加便签ID,便于后续定位具体便签 sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); // 创建延迟执行的PendingIntent(用于触发提醒) PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, sender, 0); // 获取AlarmManager服务,用于设置系统闹钟 AlarmManager alermManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); // 注册闹钟:在指定时间(alertDate)唤醒设备并发送广播 // RTC_WAKEUP模式确保在设备休眠时也能触发 alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); } while (c.moveToNext()); // 继续处理下一个便签 } // 关闭Cursor,释放资源 c.close(); } } }