0

I want to create application that will start when the device is start and will run on the background until the device will be shutdown.

I know that there are a 'services' and 'IntentService' and how to deal with them.

But i can't understand witch of them will be fit my my needed.

The service that i want to create will run on the main thread with no UI ( like the 'service' ) and do some action but this will be long turn service and from what i know .. to use a long turn service it better to use 'IntentService'

So, please any help ... how to do it ?
And how i start my service at the startup ?

Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • check this answer: http://stackoverflow.com/a/6392009/768567 – arnoduebel Aug 06 '16 at 14:56
  • For long time `Service`, you should use `startForeground()` in the `Service` – Shaishav Aug 06 '16 at 14:56
  • @Shaishav : but how i start my service at the startup – Yanshof Aug 06 '16 at 14:57
  • You listen for `BOOT_COMPLETE` intent which will fire your `BroadcastReceiver` and in your `receiver` you can call `startService()` – Shaishav Aug 06 '16 at 14:58
  • @arnoduebel - this will popup the service when some receiver signal – Yanshof Aug 06 '16 at 14:58
  • @Shaishav : still .. the service will be start when some broadcaseReceiver will be call – Yanshof Aug 06 '16 at 14:59
  • 1
    Right....however, the `receiver` will kill itself after launching the `Service` on boot. Note that booting up a device is an event and the system fires up an intent to let the apps know of this event. To capture these "events", `receivers` are the only components that can be launched in its response – Shaishav Aug 06 '16 at 15:02
  • @Shaishav : got it ... thanks ! – Yanshof Aug 06 '16 at 15:07

1 Answers1

1

IntentService is the best option for this case:

  • Requests can be handled one by one.
  • NotificationManager can meet your requirements to notify user that something happened.

In this case, you just need to call startService to start the service, and override onHandleIntent method,and it will do background work for you.

Service should be used in following cases:

  • Requests need to be handled multiple simultaneously. or
  • Components(activity or fragment) need to interact with the service. For example, to call the service APIs, to listen service callbacks. This case you should create a Bound Service.

Since your service need to run on the main thread with no UI, so you should use Service and override onStartCommand to handle request.

Refer to API Guides Services.

Weiyi
  • 1,843
  • 2
  • 22
  • 34
  • 1
    As pointed out by @Shaishav, A broadcast receiver also needs to be registered that listens for Boot_Completed which can fire up the service again. – Akil Aug 09 '16 at 08:42