问题描述
通常,当我创建 Android 服务时,我会实现 onCreate
方法,但在我的上一个项目中,这不起作用.我尝试实施 onStartCommand
,这似乎有效.
Usually when I create an Android service I implement the onCreate
method, but in my last project this does not work. I tried implementing onStartCommand
, and this seems to work.
问题是:当我必须实现一个服务时,需要哪种方法?我必须实施哪些方法?onCreate
、onStartCommand
,还是两者都有?每个人的作用是什么?
The question is: when I have to implement a service which method is required? Which methods I have to implement? onCreate
, onStartCommand
, or both? And what is the role of each?
推荐答案
onCreate()
在 Service
对象被实例化时被调用(即:当服务创建).你应该在这个方法中做你只需要做一次的事情(即:初始化一些变量等).onCreate()
只会被调用一次每个实例化对象.
onCreate()
is called when the Service
object is instantiated (ie: when the service is created). You should do things in this method that you need to do only once (ie: initialize some variables, etc.). onCreate()
will only ever be called once per instantiated object.
如果您确实想要/需要初始化某些东西只需要一次,您只需要实现 onCreate()
.
You only need to implement onCreate()
if you actually want/need to initialize something only once.
onStartCommand()
每次被调用,客户端使用startService(Intent intent)
启动服务.这意味着 onStartCommand()
可以被多次调用.您应该在此方法中执行每次客户端从您的服务请求某些内容所需的操作.这在很大程度上取决于您的服务做什么以及它如何与客户端通信(反之亦然).
onStartCommand()
is called every time a client starts the service using startService(Intent intent)
. This means that onStartCommand()
can get called multiple times. You should do the things in this method that are needed each time a client requests something from your service. This depends a lot on what your service does and how it communicates with the clients (and vice-versa).
如果你没有实现onStartCommand()
,那么你将无法从客户端传递给onStartCommand()的
并且您的服务可能无法执行任何有用的工作.Intent
中获取任何信息)
If you don't implement onStartCommand()
then you won't be able to get any information from the Intent
that the client passes to onStartCommand()
and your service might not be able to do any useful work.
这篇关于Android onCreate 或 onStartCommand 用于启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!