android: Service vs SingleTop Activity 移至后台 - 有什么区别?

标签 android service android-activity media-player


我目前正在开发一个使用 MediaPlayer 类播放 Steam 音频的应用程序。我将其主要(播放器) Activity 声明为 SingleTop。同样在“后退”按钮上,它执行 moveTaskToBack(true) ,其作用与 Home 按钮相同。所以它只是停留在后台播放,如果用户想看到 gui,他只需再次启动应用程序(不太方便),或者他单击特殊应用程序的通知。通过菜单提供退出。
但是在这种情况下使用服务而不是 Activity 有什么好处呢?开发肯定会更复杂,我不得不说。恐怕即使在“后台”时实例化 GUI 也会花费更多时间。

最佳答案

来自 Android 文档:

Activities An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails.

Services A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.

还有

Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

Android 操作系统可以在资源耗尽时销毁您的 Activity,但不会销毁服务。

编辑:您应该使用 startForeground()以确保您的 Service 不会在资源不足的情况下被终止。来自文档:

Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.

关于android: Service vs SingleTop Activity 移至后台 - 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6819577/

相关文章:

java - 刷新 ArrayList Android 应用程序

Jenkins 不是作为 Windows 服务开始的

windows-7 - 是否可以在不重新启动的情况下卸载内核驱动程序?

java - 使用 Espresso stub 在测试 Activity 的 onCreate 期间启动的 Intents

android - 为什么 onStartLoading() 调用 api 级别 >= 27 的方向更改?

android - 线性渐变和位图着色器运行不佳

android - 将 API 调用与 RX Java 相结合

android - 在运行 Oreo 和 Pie 的设备中如何在锁定屏幕上覆盖布局

android - 在另一个 Android 应用程序中从 APK 调用 Activity

在 4.4 操作系统版本的 onStart 方法中注册事件总线时出现 java.lang.NoClassDefFoundError