|
|
package net.micode.notes.ui;
|
|
|
|
|
|
import android.app.AlarmManager; // 导入AlarmManager类,用于设置闹钟
|
|
|
import android.app.PendingIntent; // 导入PendingIntent类,用于表示一个将要执行的动作
|
|
|
import android.content.BroadcastReceiver; // 导入BroadcastReceiver类,用于接收广播
|
|
|
import android.content.ContentUris; // 导入ContentUris类,用于处理URI
|
|
|
import android.content.Context; // 导入Context类,表示应用环境的全局信息
|
|
|
import android.content.Intent; // 导入Intent类,用于不同组件间的通信
|
|
|
import android.database.Cursor; // 导入Cursor类,用于遍历查询结果
|
|
|
|
|
|
import net.micode.notes.data.Notes; // 导入Notes类,用于访问笔记数据
|
|
|
import net.micode.notes.data.Notes.NoteColumns; // 导入NoteColumns类,包含笔记表的列名
|
|
|
|
|
|
// 定义一个广播接收器,用于初始化闹钟
|
|
|
public class AlarmInitReceiver extends BroadcastReceiver {
|
|
|
|
|
|
// 定义查询笔记时需要返回的列
|
|
|
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; // 提醒日期的索引
|
|
|
|
|
|
// 当接收到广播时调用此方法
|
|
|
@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,用于触发AlarmReceiver广播接收器
|
|
|
Intent sender = new Intent(context, AlarmReceiver.class);
|
|
|
// 设置Intent的URI,包含笔记的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);
|
|
|
// 设置闹钟,在提醒日期时触发广播
|
|
|
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
|
|
|
} while (c.moveToNext()); // 继续遍历查询结果
|
|
|
}
|
|
|
c.close(); // 关闭Cursor
|
|
|
}
|
|
|
}
|
|
|
}
|