Android服务,我们必须使用startService还是BindService?
Android Service, do we have to use startService or BindService?
我正在开发 MusicPlayer 应用程序,我使用本地服务在后台制作 MediaPlayer 运行。看来我们既可以发送启动服务的意图,也可以绑定服务。我理解对于 startService 的意义,我们将其保留 运行ning 并将意图发送到 stopService,对于 bindService,我们取回 IBinder 以与服务通信。但是,我想知道这样做有什么意义?我们是否必须发送意图才能使其工作?
如果我只是获取一个Service的静态实例,直接调用它的方法,我也可以同时实现启动它和与它通信。
我找到了一个不使用 startService 和 bindService 的示例,但它作为一个简单的 MusicPlayer 效果很好。
However, I'm wondering what's the point of doing this?
让服务成为运行,告诉OS"hey, we are doing work here on behalf of the user, please let my process live a bit longer"。
这在 the documentation 中有介绍。
Do we have to send intents to make it work?
是的。
If I just retrieve an static instance of Service, and directly call its methods, I can also implement both start it and communicate with it.
那么它只是一个Java对象,没有继承Service
的意义。此外,这意味着当您的 UI 不在前台时,您的进程将存活更短的时间。
I found an example of not using startService nor bindService, but it works well as a simple MusicPlayer.
服务已启动,通过startService()
、in ArtistSearchActivity
。在此之前,服务不存在,单例将是 null
.
startService 在不需要与服务通信时使用。
BindService 在需要通信的时候使用。
在你的应用程序中,我认为你会与服务进行通信(例如,如果你有一个 activity 选择歌曲的地方,你将向服务发送数据说:"this is the song which you have to play now") 并且我认为您将需要 BindService 而不是 startService。
希望对您有所帮助:D
我正在开发 MusicPlayer 应用程序,我使用本地服务在后台制作 MediaPlayer 运行。看来我们既可以发送启动服务的意图,也可以绑定服务。我理解对于 startService 的意义,我们将其保留 运行ning 并将意图发送到 stopService,对于 bindService,我们取回 IBinder 以与服务通信。但是,我想知道这样做有什么意义?我们是否必须发送意图才能使其工作? 如果我只是获取一个Service的静态实例,直接调用它的方法,我也可以同时实现启动它和与它通信。
我找到了一个不使用 startService 和 bindService 的示例,但它作为一个简单的 MusicPlayer 效果很好。
However, I'm wondering what's the point of doing this?
让服务成为运行,告诉OS"hey, we are doing work here on behalf of the user, please let my process live a bit longer"。
这在 the documentation 中有介绍。
Do we have to send intents to make it work?
是的。
If I just retrieve an static instance of Service, and directly call its methods, I can also implement both start it and communicate with it.
那么它只是一个Java对象,没有继承Service
的意义。此外,这意味着当您的 UI 不在前台时,您的进程将存活更短的时间。
I found an example of not using startService nor bindService, but it works well as a simple MusicPlayer.
服务已启动,通过startService()
、in ArtistSearchActivity
。在此之前,服务不存在,单例将是 null
.
startService 在不需要与服务通信时使用。 BindService 在需要通信的时候使用。
在你的应用程序中,我认为你会与服务进行通信(例如,如果你有一个 activity 选择歌曲的地方,你将向服务发送数据说:"this is the song which you have to play now") 并且我认为您将需要 BindService 而不是 startService。
希望对您有所帮助:D