Consider the following sequence of events :
- A
BroadcastReceiveris registered in theonResumemethod of anActivity(without a handler). - A
CursorLoaderis started by calling therestartLoadermethod as the next immediate statement inonResume(restartLoaderis 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 :
- There is a foreground service already running in the background that is publishing messages for my
BroadcastRecievereven before the app is launched for the first time AND - Considering that the
BroadcastRecieveris registered before theCursorLoaderis started, shouldn't theonReceivemethod get triggered immediately considering there are already messages available for theBroadcastReceiver.
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.
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