AlarmInitReceiver是一个BroadcastReceiver,用于初始化闹钟。当接收到广播时,它会查询数据库中所有需要提醒(提醒日期大于当前时间)且类型为普通笔记的条目。对于每个符合条件的笔记,它会创建一个PendingIntent,并使用AlarmManager设置一个闹钟,该闹钟在笔记的提醒日期到达时触发。当闹钟触发时,会广播一个Intent,该Intent被AlarmReceiver(未在代码中定义,但假设存在)接收并处理,通常用于显示提醒通知。

zhangli1
LZ 4 weeks ago
parent 0da440a0ac
commit 873438d8f3

@ -0,0 +1,76 @@
/*
* 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;
// 导入所需的Android和自定义类
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;
// 定义一个继承自BroadcastReceiver的类用于初始化闹钟
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用于在提醒时间到达时广播
Intent sender = new Intent(context, AlarmReceiver.class);
// 设置Intent的URI包含笔记的ID
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建一个PendingIntent用于AlarmManager在提醒时间到达时启动
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取AlarmManager服务
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 设置闹钟在提醒时间到达时广播Intent
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 处理查询结果中的下一条记录
}
c.close(); // 关闭Cursor
}
}
}
Loading…
Cancel
Save