哪个 android activity 应该保存其他活动使用的对象?

Which android activity should hold objects used by other activites?

我想知道,在 android 活动中创建和保存对象的好地方在哪里?总是 activity 层级中的最高层?这就是我的意思。

/* 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 的对象之一,我从来没有遇到过任何问题。但是这种情况总是有效吗?当子 activity 可见时,来自父 activity 的对象是否始终保留在内存中?

我能否以某种方式将对 someList 的引用从 activity1 传递到 activity2 并假装 someList 已在 activity2 中实例化?或者这不是必需的?

另一方面,

activityX 显然会在应用程序(因此 activity1)不在后台 运行(或者只是没有缓存?)时创建空指针异常。 .

是否有包含此类内容的 android 编程指南文档?

让我们看看..

/* 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?
  ...
}

只要满足几个条件,可能 有效:

  • 只有activity1activity2之前启动才有效,否则someList为空,因为它还没有被创建。

  • 如果android决定杀死你的activity1someList将为空。 (如果内存不足,可能会发生这种情况,例如,如果您的 activity2 使用大量内存。)

Will the objects from a parent activity always stay in memory while the child activity is visible?

不,它们可能不会留在内存中,因为 android 可以杀死你的 activity,它在任何时候都不可见。 (虽然这通常不会发生,因为大多数设备都有足够的内存)


/* 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 将为空。 (如果你的 activity 不是 运行 在后台,它会生成一个 NullPointerException


不要指望您的应用是 运行,因为 android 系统可能随时终止您的应用

如果可能,您应该通过意图传输数据或根据需要重新创建。如果你想通过intent传输数组/列表,Intent class提供ways of doing this. If you really need to transfer objects, you should use Parcelable. See here.

有一个关于此的有趣话题 here

哦,内存泄漏: 例如,如果您有一个内部 class,并在您的 activity 中将其实例化为静态变量,您将发生内存泄漏,因为静态变量的寿命将超过 activity。 (请参阅 here 以获得更好的解释)