I have a service that needs to notify the main activity. I use LocalBroadcastManager, and it works fine, but LocalBroadcastManager has been deprecated.
This is my actual code in the service:
public void onTokenRefresh() {
/* build the intent */
Intent intent = new Intent(ACTION_TOKENREFRESHED);
intent.putExtra("token", "xxx");
/* send the data to registered receivers */
try{
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} catch (Throwable e){
//no exception handling
}
}
In the main activity, I get informed of the notification like this :
context.registerReceiver(broadcastReceiver, intentFilter);
What can I use now to remove the deprecated warning? All examples I found regarding sending data from service to activity use LocalBroadcastManager. Can someone give me a workable model for migrating my existing code?
NOTE
In my example, The onTokenRefresh is called from inside a background thread. That is very important because it means I can simultaneously receive several onTokenRefresh, and I must forward all these tokens to the activity. Most of the offered solutions use live data but make a declaration like :
public static final MutableLiveData<String> tokenLiveData = new MutableLiveData<>();
Background Thread1:
tokenLiveData.postValue(Token1);
Background Thread2 (at same time):
tokenLiveData.postValue(Token2);
Will forward ALL tokens received simultaneously to the main activity that observes the tokenLiveData? Will the main activity always receive for sure token1 and token2?
Make a
serviceclass and define aLiveDatato replace theLocalBroadcastManagerresponsibility like so:Then start the
servicein theactivityand observe theLiveDatalike below:You can also
starttheservicefromanother activityand observe it in theMainActivity;