BroadcastReceivers 在侦听 BOOT_COMPLETED 时接收到哪个上下文?

Which context does BroadcastReceivers receive when listening for BOOT_COMPLETED?

Android 中的 AlarmManager 在 phone 断电时会丢失所有已注册的警报。

我使用以下广播接收器在 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();
        }
    }
}

您的 BroadcastReceiver 接收哪种类型的 Context 并不重要(无论如何,它的 ApplicationContext),因为: 1) 您不应使用与 Activity 关联的 DBHelper。相反,将其设为 Singleton 并在整个应用程序中使用它。 2) 你的 AlarmManager 应该使用 Service 来设置。因此,最好在 onReceive() 中调用该服务并从该服务设置警报

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 已正确设置,很容易做一些愚蠢的事情。您最好将此类静态方法移动到通用实用程序 class,它不是 Activity,只包含 static 方法。这样看起来就不那么可疑了。