/* * 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 { //声明PROJECTION,每个元素包括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; //AlarmInitReceiver的配置“android.intent.action.BOOT_COMPLETED”,表明 // Android手机开机后,会发送android.intent.action.BOOT_COMPLETED广播,监听这个广播就能监听开机。 // 开机之后,就处理已有的便签,逐条比较日期,如果有到期的,就用AlarmManager提醒用户。 @Override //2. 接收广播后的处理方法,上下文context,消息传递工具intent public void onReceive(Context context, Intent intent) { //System.currentTimeMillis()产生一个当前的毫秒 long currentDate = System.currentTimeMillis(); //Cursor在这里的作用是通过查找数据库中的标签内容,找到和当前系统时间相等的标签 Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, PROJECTION, //获取的是当前时间大于设置提醒时间的便签项 NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, //类型转换,将long类型的currentDate转变为String类 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); // 设置新的便签的uri和id sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); //设置闹钟 当提醒时间到达时发送Intent并且唤醒设备 AlarmManager alermManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); } while (c.moveToNext());//游标移动到下一位置 } c.close(); } } }