Android onCreate or onStartCommand for starting service

◇◆丶佛笑我妖孽 提交于 2019-11-26 06:25:13

问题


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.

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?


回答1:


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.

You only need to implement onCreate() if you actually want/need to initialize something only once.

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).

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.




回答2:


Service behave same like Activity Whatever you want to associate once with a service will go in onCreate like initialization

and whenever the service is called using startService. onStartCommand will be called. and you can pass any action to perform . like for a music player , You can play ,pause,stop using action

And you do any operation in service by sending an action and receiving it on onStartCommand

onCreate work like a Constructor.

Edit in Short

onCreate() calls only for the first time you start a Service Whereas onStartCommand() calls everytime you call the startService again. It let you set an action like play,stop,pause music.

public void onStartCommand()
{
     if(intent.getAction.equals("any.play")
     {
        //play song
     }
     else if(intent.getAction.equals("any.stop")
     {}
}


来源:https://stackoverflow.com/questions/14182014/android-oncreate-or-onstartcommand-for-starting-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!