/* * 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. */ // AlarmReceiver.java - 闹钟触发广播接收器 // 主要功能:接收系统闹钟触发广播,启动闹钟提醒Activity package net.micode.notes.ui; // ======================= 导入区域 ======================= // Android广播相关 import android.content.BroadcastReceiver; // 广播接收器基类 import android.content.Context; // 上下文 import android.content.Intent; // 意图,用于启动Activity // ======================= 闹钟触发广播接收器 ======================= /** * AlarmReceiver - 闹钟触发广播接收器 * 继承自BroadcastReceiver,接收系统闹钟触发的广播 * 主要功能:将系统闹钟广播转换为启动AlarmAlertActivity * * AndroidManifest.xml中注册: * * * 独立进程运行,确保即使主进程被杀死也能接收闹钟 */ public class AlarmReceiver extends BroadcastReceiver { /** * onReceive - 广播接收回调方法 * 当系统闹钟触发时被调用 * 执行流程: * 1. 修改Intent的目标类为AlarmAlertActivity * 2. 添加NEW_TASK标志 * 3. 启动闹钟提醒Activity * * 工作流程: * 系统闹钟触发 → AlarmReceiver接收 → 启动AlarmAlertActivity → 显示提醒 * * @param context 广播接收器的上下文 * @param intent 接收到的广播意图,包含以下信息: * - Data URI: content://micode_notes/note/{noteId} (来自AlarmInitReceiver的设置) * - 可能包含其他闹钟相关数据 */ @Override public void onReceive(Context context, Intent intent) { // 1. 修改Intent的目标Activity类 // 原始Intent来自AlarmInitReceiver设置的PendingIntent // 这里将目标类改为AlarmAlertActivity intent.setClass(context, AlarmAlertActivity.class); // 2. 添加NEW_TASK标志 // 原因:从广播接收器启动Activity必须在独立任务栈中 // FLAG_ACTIVITY_NEW_TASK作用: // - 创建新的任务栈 // - 允许从非Activity上下文(BroadcastReceiver)启动Activity // - 避免与现有Activity的任务栈冲突 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 3. 启动闹钟提醒Activity // 启动后,AlarmAlertActivity将显示全屏提醒对话框 context.startActivity(intent); } }