当手机断电时,Android 中的 AlarmManager 会丢失所有已注册的警报。
我使用以下广播接收器在 android 启动时触发:
public class AlarmBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Cursor alarmCursor = MainActivity.dbHelper.loadAlarms();
// Iterate through every stored alarm and set those alarms.
// ....
alarmCursor.close();
}
}
}
当广播接收器的 onReceive 在系统启动时被触发时,给该方法的上下文参数是什么?我必须知道上下文,因为我需要上下文来取消在该上下文中设置的警报。
我假设调用 MainActivity.dbHelper.loadAlarms() 是不安全的,因为 MainActivity 未在系统启动时初始化。或者它是否安全,因为 dbhelper 和 loadAlarms() 都已初始化并声明为静态?
最佳答案
When the broadcast receiver's
onReceive
is triggered at system bootup, what context parameter is given to the method? I have to know the context, because I need the context to cancel alarms set in that context.
在这种情况下,您将在 onReceive()
中获取全局应用程序 Context
。但是,这无关紧要。你不需要知道。
要稍后取消警报,您将创建一个PendingIntent
,您可以使用任何您想要执行此操作的Context
。警报未链接到特定的 Context
,它们仅链接到特定的应用程序。
I am assuming the call to MainActivity.dbHelper.loadAlarms() is not safe because MainActivity is not initialized in system bootup. Or is it safe because dbhelper and loadAlarms() are all initialized and declared
static
?
如果 dbHelper
确实是 static
并且在实例创建时初始化(不在 onCreate()
中),那么这个电话很好。一般来说,在 Activity 上调用静态方法是不受欢迎的,因为假设 Activity
已正确设置,很容易做一些愚蠢的事情。您最好将此类静态方法移动到通用实用程序类,该类不是 Activity
并且仅包含 static
方法。这看起来不那么可疑。
关于android - BroadcastReceivers 在监听 BOOT_COMPLETED 时接收到哪个上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41318239/