/* * 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. */ /** * * @ProjectName: $MiNotes$ * @Package: $ui$ * @ClassName: $AlarmInitReciver.java$ * @Description: 该类主要功能是根据数据库里的闹钟时间创建一个闹钟机制 * @Author: 石兆羲 * @CreateDate: $2023/12/23$ */ 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 { 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; @Override public void onReceive(Context context, Intent intent) { long currentDate = System.currentTimeMillis(); //System.currentTimeMillis()函数的作用是产生一个当前的毫秒 //毫秒数是自1970年1月1日0时起的毫秒数 Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, //Cursor在这里的作用是通过查找数据库中的标签内容,找到和当前系统时间相等的标签 //通过 context.getContentResolver() 获取当前应用程序的 ContentResolver 对象 //使用 query() 方法对系统中的 Notes 数据库进行查询操作。 //其中,Notes.CONTENT_NOTE_URI 是一个常量,表示 Notes 数据库中的笔记表对应的 Uri 地址。 PROJECTION,//字符串数组,包含查询结果的列名 NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, //这里定义了两个查询条件: //笔记的提醒日期晚于某个特定时间; //笔记的类型为 Notes.TYPE_NOTE new String[] { String.valueOf(currentDate) }, //将long变量currentDate转化为字符串 null); if (c != null) { if (c.moveToFirst()) { do { long alertDate = c.getLong(COLUMN_ALERTED_DATE); Intent sender = new Intent(context, AlarmReceiver.class); //Intent用于在不同组件之间传递消息、启动服务、启动活动等。 sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); //PendingIntent通常用于在未来的某个时间点执行某项操作,比如在特定的时刻启动一个 Activity、发送一个广播或者启动一个服务。 AlarmManager alermManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); //AlarmManager用于在指定的时间点触发某个操作。它可以用来实现定时任务、闹钟提醒、周期性任务等功能。 //通过网上查找资料发现,对于闹钟机制的启动,通常需要上面的几个步骤,如新建Intent、PendingIntent以及AlarmManager等 } while (c.moveToNext()); } c.close(); } } }