Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onCreate or onStartCommand for starting service

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?

like image 837
GVillani82 Avatar asked Jan 06 '13 12:01

GVillani82


People also ask

How do I start a service in Android?

Starting a service You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.

What are the return values of on Start command in Android services?

The documentation says: For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY. So returning super. onStartCommand() is equivalent to returning START_STICKY .

How do I declare a service in manifest Android?

You declare a service in your app's Manifest, by adding a <service> element as a child of your <application> element. There's a list of attributes that you can use to control a service's behavior, but as a minimum you'll need to provide the service's name (android:name) and a description (android:description).

When onCreate function is called in Android?

onCreate() will be called after pressing back button, while it's going background and can be disposed by system if more ram is needed.


1 Answers

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.

like image 99
David Wasser Avatar answered Sep 21 '22 17:09

David Wasser