我想知道,在Android活动中创建和保存对象的好地方在哪里?始终是层次结构中最高的活动?这就是我的意思。
/* Let this be the main launcher activity */
activity1{
List someList // Edit: This should of course be public, my mistake.
}
/* The next activity is a child of activity1
* and can be started by activity 1
*/
activity2{
...
do_something(activity1.someList); // Does this always work?
...
}
/* The next activity has no parent and can be launched
* when the app receives an intent, for example a
* photo is shared to my app.
*/
activityX{
....
receive_intent(...);
do_something(activity1.someList) // This might work, when app is already running
}
看,我的问题是我不确定放置物品的位置。在我的示例中activity2
需要访问activity1的一个对象,我从来没有遇到任何问题。但这种情况总是有效吗?当子活动可见时,来自父活动的对象是否总是留在内存中?
我可以以某种方式将someList
的引用从activity1
传递给activity2
并假装someList
已在activity2
中实例化了吗?或者这不是必需的吗?
activity1
)没有在后台运行(或者只是没有缓存?)时,activityX显然会创建一个nullpointer异常。
是否有一个包含Android编程指南的文档,涵盖了这样的内容?
答案 0 :(得分:1)
/* Let this be the main launcher activity */ activity1{ List someList }
您可能希望将List
声明为public
和/或static
/* The next activity is a child of activity1 * and can be started by activity 1 */ activity2{ ... do_something(activity1.someList); // Does this always work? ... }
如果满足一些条件,可能可以工作:
仅当activity1
在 activity2
之前启动时才会有效,否则someList
将为空,因为它尚未创建
如果Android决定杀死您的activity1
,someList
将为空。 (如果内存不足,可能会发生这种情况,例如,如果你的activity2
占用大量内存。)
当子活动可见时,来自父活动的对象是否始终保留在内存中?
不,他们可能不会留在记忆中,因为安卓可以杀死你在任何时候都看不到的活动。 (但这通常不会发生,因为大多数设备都有足够的内存)
/* The next activity has no parent and can be launched * when the app receives an intent, for example a * photo is shared to my app. */ activityX{ .... receive_intent(...); do_something(activity1.someList) // This might work, when app is already running }
如果您的用户在未首先启动应用的情况下共享照片,该怎么办? ... SomeList
将为空。 (如果您的活动未在后台运行,它将生成NullPointerException
不要依赖您的应用运行,因为Android系统可能会随时杀死您的应用
如果可能,您应该通过意图传输数据或根据需要重新创建。如果要通过intent传输数组/列表,Intent
类提供ways of doing this。如果您确实需要传输对象,则应使用Parcelable
。请参阅here。
关于这个here有一个有趣的主题。
哦,内存泄漏: 例如,如果您有一个内部类,并将其实例化为活动中的静态变量,则会出现内存泄漏,因为静态变量将比活动更长。 (有关更好的解释,请参阅here)