Android的服务Android

2023-09-12 23:42:11 作者:情圣

请解释一下一个Android 服务。它是如何从活动有什么不同?它依赖于应用程序的状态,如在前台/后台运行

Please explain an Android Service. How does it differ from an Activity? Does it depend on an application state such as running in the foreground/background?

推荐答案

从为 Android开发者的SDK参考服务:

一个服务是一种应用程序组件重新presenting无论是应用程序的愿望,执行长时间运行的操作,而不是与用户交互或提供功能的其他应用程序使用。

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

要注意的是非常重要的

这是服务,如其他应用程序对象,在其宿主进程的主线程中运行。这意味着,如果你的服务是打算做任何CPU密集型(如MP3播放)或阻塞(如网络)业务,它应该产卵在做这项工作自己的线程。

that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.

这是相对于其中最好被理解为一些用户直接看见并用相互作用的活性(的UI。)

This is in contrast to an activity which is best understood as something a user directly sees and interacts with (a UI.)

有一个服务,如上面提到的,可用于长期运行的操作,如果你没有前台活动,将继续连,但他们可以,而且最终将通过Android的生命周期,如果留在后台状态被杀死。如果您需要的服务,持续运行的一个实例没有被打死,重新启动后,我会建议把startForeground(int ID,通知通告)在你的服务的的onCreate 方法和stopForeground(boolean removeNotification)在你的服务的的onDestroy 方法。

A service, as mentioned above, can be used for longer-running operations that will continue even if you have no foreground activity, but they can, and eventually will be killed by Android's lifecycle if left in the "background" state. If you need your service to continue running as a single instance without being killed and restarted, I would recommend placing startForeground(int id, Notification notification) in your Service's onCreate method and stopForeground(boolean removeNotification) in your Service's onDestroy method.

例如,我有一个使用前台服务来记录加速计数据整夜而Android设备用户旁边的身体的应用程序。虽然它不要求激活,我也有一个活动是广播的意图的BroadcastReceiver 服务,它告诉服务,它应该还播放了意图与加速计数据作为群众演员到的BroadcastReceiver 活动里面

For example, I have an app that uses a foreground Service to record accelerometer data all night while the android device is next to the user's body. Though it is not required to be active, I also have an Activity that broadcast an Intent to a BroadcastReceiver inside the Service which tells the Service that it should also broadcast an Intent with accelerometer data as extras to a BroadcastReceiver inside the Activity.

code: SleepActivity SleepAccelerometerService

祝你好运,让我知道如果你需要更多的信息!

Good luck and let me know if you need any more information!