使用LocalBroadcastManager发送PendingResult引用(对于有序广播)

时间:2016-06-10 14:36:43

标签: android android-intent parcelable localbroadcastmanager

我想通过LocalBroadcastManager发送PendingResult,因为LocalBroadcastManager似乎不支持有序广播。

我可以创建一个实现Parcelable的包装器对象,它包含对PendingResult的内存引用,然后将它粘贴到Intent(根本没有任何序列化)吗?问题实际上是:当使用LocalBroadcastManager通过Intents发送Parcelables时,对象内存引用是否完整,即LocalBroadcastManager是否真的只将Intent Object引用转发到我应用程序中的不同位置?

或者

有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

这可以通过Android Hidden API libraryResourcesHolder课程来完成。尽管该库是为访问内部API而设计的,但是发送任何对象是其能力之一。看看这个例子:

ResourcesHolder holder = new ResourcesHolder()
    // you also able to put multi-object, but give each of them different 'key'
    .put("pi1", myPendingIntent1)
    .put("pi2", myPendingIntent2);

// send via context.sendBroadcast(intent)
holder.sendBroadcast(context, "myKey");

// or send via LocalBroadcastManager
holder.sendViaLocalBroadcastManager(context, "myKey");

// don't forget to register your receiver with IntentFilter ResourcesHolder.ACTION_SEND_RESOURCES_HOLDER

BroadcastReceiver

// to get them back:
if (intent.getAction().equals(ResourcesHolder.ACTION_SEND_RESOURCES_HOLDER){
    ResourcesHolder holder = intent.getParcelableExtra("myKey");
    PendingIntent pi1 = (PendingIntent) holder.getAsObject("pi1");
    PendingIntent pi2 = (PendingIntent) holder.getAsObject("pi2");
}

答案 1 :(得分:0)

我为PendingResult制作了一个Parcelable包装器:

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;
    }

}

它可以绑定到Intent并由LocalBroadcastManager作为Object引用进行广播,因为本地广播从未真正序列化,与进程间广播不同。

有效!