问题描述
通常,当我创建一个机器人服务,我实现了的onCreate
的方法,但在我的最后一个项目,这并不正常工作。我试图实施 onStartCommand
,这似乎工作。
Usually when I create an android service I implement the onCreate
method, but in the 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()
被调用的时候,服务
对象实例化(即:当服务的创建)。你应该做的事情在这个方法中,你需要做的只有一次(即:初始化一些变量等)。 的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(意向意图)
。这意味着 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()
,那么你将无法获得从意图$ C $的任何信息C>客户端传递到
onStartCommand()
和你的服务可能无法做任何有用的工作。
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.
这篇关于安卓的onCreate或onStartCommand启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!