Precedence of Loaders vs BroadcastReceivers started on the main thread

55 views Asked by At

Consider the following sequence of events :

  1. A BroadcastReceiver is registered in the onResume method of an Activity (without a handler).
  2. A CursorLoader is started by calling the restartLoader method as the next immediate statement in onResume (restartLoader is called on the main thread itself)

My observations is that onLoadFinished method always gets called before the first call to onReceive. That is, the CursorLoader takes precedence over the BroadcastReciever. Moreover, the onReceive method of the BroadcastReceiver does not get called until the onLoadFinished method completes.

Assuming that :

  1. There is a foreground service already running in the background that is publishing messages for my BroadcastReciever even before the app is launched for the first time AND
  2. Considering that the BroadcastReciever is registered before the CursorLoader is started, shouldn't the onReceive method get triggered immediately considering there are already messages available for the BroadcastReceiver.

Since this is not the case, I am lead to believe that the CursorLoader takes precedence over a BroadcastReceiver when started on the main thread of an activity. However, I can't seem to find any documentaiton for this.

How can I ensure that my BroadcastReceiver gets precedence over the CursorLoader? This behavior is important because I want my Activity to be initialized with some information that is being broadcasted by the foreground service even if the app is being launched newly (i.e onCreate being called on the ACtivity). The CursorLoader needs this information to create the Uri to be used for fetching the relevant data and showing it on the UI. Since the CursorLoader runs before the BroadcastReciever, it constructs a Uri without this information and subsequently fetches stale data from the database.

1

There are 1 answers

3
Jordan On

Loaders are deprecated and would highly suggest refactoring to use ViewModel. You can also use Live Data in Conjunction.

Link to ViewModel ViewModel Overview Link to Live Data LiveData Overview