Android:单例而不是服务

Android: Singleton instead of a Service

我今天正在采访其中一位候选人。我问了一个很常见的问题:如何向 Android 应用程序添加持续播放音乐的可能性,即使 activity 在 phone 方向改变时被破坏。预期的答案是:创建负责播放音乐的服务。而不是那个候选人建议在应用程序中创建一些单身人士。

这也是正确答案吗?我认为它应该可以工作 - Singleton class 将加载到内存中并永远保留在内存中;我的同事建议这个单例将被销毁 activity,因为将不再有任何引用。

Is this also a correct answer?

恕我直言,没有。

Singleton class will be load to memory and will stay in memory forever

没有。 Processes get terminated 当它们不再位于前台时,为其他应用程序释放系统 RAM。确定发生这种情况的确切时间取决于很多变量...其中之一是您是否有 运行 Service.

my colleague suggest this singleton will be destroy with destroyed activity, because there won't be any reference any longer.

没有。 Java 中的单例实现为 static 字段。只要该字段具有对该对象的引用,该对象就不能被垃圾回收。默认情况下,仅销毁 activity 不会神奇地将 static 字段设置为 null.

创建防止应用程序上下文被破坏的后台任务的唯一方法是 run a Service in the foreground 通过显示通知用户它是 运行 的持续通知。给出的示例或多或少正是您要求候选人提供的内容:

For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.

此外,单例存在于全局范围内,并且与全局范围存在的时间一样长 - 通常直到 Android 终止您的应用程序,因为它不是 运行 任何前台任务,而不是当 Activity 使用它的人会被清理干净。