/* * 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. */ // 定义一个广播接收器,用于初始化闹钟 public class AlarmInitReceiver extends BroadcastReceiver { // 静态字段,定义投影的列 private static final String [] PROJECTION = new String [] { NoteColumns.ID, NoteColumns.ALERTED_DATE }; // 定义投影列的索引 private static final int COLUMN_ID = 0; 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); // 创建一个意图,指向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.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(); } } }