13

I know similar questions have been asked multiple times. I think i read most of it. But none answer is applicable.

I need to pass complex Objects via Intents (Activity calls/Broadcasts). Everything is done within my process. That's why I see no reason to write my objects into Streams just to reassemble them a few milliseconds after. I want to pass my object reference through my application. Is there any way to do this.

Since my application will broadcast the same Event multiple times in a row I can't rely on static members. I need to get exacly the same object for what I broadcasted.

That's why I was thinking about a static "Referenceholder" that will accept an Object and return an integer that identifies this object in it's internal list so I can pass this integer via .putExtras. But as far as I know Java I could not clean up this Object from this list after it has been added because multiple Listeners could be interessted in the very same object and I would have to keep it in my Referenceholder for ever (assuming that a thread may be resumed at any time - even 2 minutes later).

Any ideas? Am I doing something wrong? Or any ideas of how I can clean up my referneces (probably after some seconds? this may lead to a crash but it seems to be more applicable than writing code that assembles and reassembles my objects for no reason)

4

2 回答 2

7

您的选择非常明确:无法在 Intent 中传递不可编组的对象(Parcelable、Serializable)。句号。

您可能能够做的是传递一些对不可编组对象的引用。这个想法是,您将按照将键传递给映射的顺序执行某些操作,该映射将该键映射到您有兴趣传递的值。如果 Intent 发送者和 Intent 接收者都可以访问地图,则可以传达对不可编组对象的引用。

我不明白,为什么你认为静态成员不是你想要的。我猜想自定义应用程序对象中的静态地图几乎正是您想要的。...我怀疑,从您对 WeakHashMaps 的评论中,您已经发现了这一点。

...除了到目前为止你所说的没有解释为什么你想让你的地图变弱。在使用弱映射之前,请查看软引用,以确保这不是您的意思。

祝你好运

于 2013-02-17T02:01:14.633 回答
4

编辑:

忘记这个解决方案。这没用。Android 正在处理您在 .startActivity() 中传递的 Intent。没有办法在活动中获得任何引用。这是 - 在我看来 - 很棒,但我的谷歌。您必须调用您的活动并将对象的引用放置在静态成员中......

正如 G. Blake Meike 所提到的,在 Android 中无法通过 Intents 传递对象引用。但是您也许可以使用Wea​​kReferences

关于这个主题的一篇非常优秀的文章可以在这里找到: http ://weblogs.java.net/blog/2006/05/04/understanding-weak-references

我通过这个问题得到了解决方案: 是否可以获得对象引用计数?

所以我基本上要做的是:我将使用 Intents 作为WeakHashMap的 Key并将我的 Object 作为值传递。这似乎是唯一适合作为 Key 的对象,因为您放入 Intents extras 的所有内容都将被序列化。因此,每个 Intent 只能传递一个对象。你可以在你的 Acitivity 中实现子类来保存你的对象,然后把这个子类放到地图中。但是我仍然不确定接收者将获得的 Intent 对象是否与调用者创建的相同,但我认为是的。如果不是,我将编辑此解决方案(或者也许有人可以清除它)。

于 2013-02-17T02:29:21.070 回答