Search code examples
androidandroid-intentparcelablelocalbroadcastmanager

Use LocalBroadcastManager to send PendingResult reference (for ordered broadcasts)


I want to send a PendingResult via a LocalBroadcastManager since ordered broadcasts doesn't seem to be supported with LocalBroadcastManager.

Can I make a wrapper object that implements Parcelable, which contains a memory reference to a PendingResult and then stick it to an Intent (without any serialization at all)? The question really is: Will Object memory references be intact when sending Parcelables via Intents using LocalBroadcastManager, i.e. does LocalBroadcastManager really only forward Intent Object references to different places within my app?

Or

Is there a better way to do this?


Solution

  • I made a Parcelable wrapper for PendingResult as such:

    public class PendingResultWrapper implements Parcelable {
    
        private BroadcastReceiver.PendingResult pendingResult; //The only thing we care about in this class!
    
        public PendingResultWrapper(BroadcastReceiver.PendingResult pendingResult) {
            this.pendingResult = pendingResult;
        }
    
        protected PendingResultWrapper(Parcel in) {
        }
    
        public static final Creator<PendingResultWrapper> CREATOR = new Creator<PendingResultWrapper>() {
            @Override
            public PendingResultWrapper createFromParcel(Parcel in) {
                return new PendingResultWrapper(in);
            }
    
            @Override
            public PendingResultWrapper[] newArray(int size) {
                return new PendingResultWrapper[size];
            }
        };
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel parcel, int i) {
        }
    
        public BroadcastReceiver.PendingResult getPendingResult() {
            return pendingResult;
        }
    
    }
    

    It can be strapped to an Intent and broadcasted by a LocalBroadcastManager as an Object reference because local broadcasts are never really serialized, unlike inter-process broadcasts.

    It works!