launcher3: Improve SimpleBroadcastReceiver.

Unless explicitly annotated, parameters in java are by
  default nullable. There are a few cases where a null context
  may be passed to the unregisterReceiverSafely function
  of SimpleBroadcastReceiver.

  To mitigate misuses or incorrect contexts being passed for
  register vs unregister, keep the context as a strong reference
  in the constructor.

  Also added NonNull annotations for any public callsites to
  enforce behavior.

Bug: 395019017, 395966395
Flag: NONE - bug fixed
Test: manual - presubmit
Change-Id: Ie371fa45cadceaf51cf184b446df9123ef27c337
This commit is contained in:
Adnan Begovic
2025-02-11 16:03:45 -08:00
parent 4425ab3062
commit 1b26bb4a74
16 changed files with 118 additions and 113 deletions
@@ -46,34 +46,31 @@ public class ScreenOnTracker implements SafeCloseable {
private final SimpleBroadcastReceiver mReceiver;
private final CopyOnWriteArrayList<ScreenOnListener> mListeners = new CopyOnWriteArrayList<>();
private final Context mContext;
private boolean mIsScreenOn;
@Inject
ScreenOnTracker(@ApplicationContext Context context, DaggerSingletonTracker tracker) {
// Assume that the screen is on to begin with
mContext = context;
mReceiver = new SimpleBroadcastReceiver(UI_HELPER_EXECUTOR, this::onReceive);
mReceiver = new SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR, this::onReceive);
init(tracker);
}
@VisibleForTesting
ScreenOnTracker(@ApplicationContext Context context, SimpleBroadcastReceiver receiver,
DaggerSingletonTracker tracker) {
mContext = context;
mReceiver = receiver;
init(tracker);
}
private void init(DaggerSingletonTracker tracker) {
mIsScreenOn = true;
mReceiver.register(mContext, ACTION_SCREEN_ON, ACTION_SCREEN_OFF, ACTION_USER_PRESENT);
mReceiver.register(ACTION_SCREEN_ON, ACTION_SCREEN_OFF, ACTION_USER_PRESENT);
tracker.addCloseable(this);
}
@Override
public void close() {
mReceiver.unregisterReceiverSafely(mContext);
mReceiver.unregisterReceiverSafely();
}
@VisibleForTesting