1

I analysed the Android tutorial, which says to start service on receive for long running operation >10sec, but isn't service running from main thread?

http://developer.android.com/guide/practices/responsiveness.html#avoiding

Service (http://developer.android.com/reference/android/app/Service.html)

It also says don't do long time operation; which one is more appropriate then?

halfer
  • 19,824
  • 17
  • 99
  • 186
David Prun
  • 8,203
  • 16
  • 60
  • 86
  • 1
    Service does not have a Ui thread. ANR is only for UI threads. So it is safe to do long operations in service – nandeesh Aug 15 '12 at 18:51
  • 1
    @nandeesh: Services most certainly run on the main application thread. `onCreate()`, `onStartCommand()`, `onBind()`, and `onDestroy()` are called on the same "UI thread" that the activities of the app use. "So it is safe to do long operations in service" -- only if that is an `IntentService`, or if you fork your own thread. – CommonsWare Aug 15 '12 at 21:07
  • @CommonsWare i hadnt thought about it that way. You are right. Thanks!! – nandeesh Aug 15 '12 at 22:10

1 Answers1

1

but isn't service running from main thread?

The lifecycle methods of a Service (e.g., onStartCommand()) are called on the main application thread. However, a Service, unlike a manifest-registered BroadcastReceiver, can safely fork background threads. An IntentService does this automatically, which is why it is ideal for pairing with a manifest-registered BroadcastReceiver in many scenarios.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Is it better to use service or Intentservice? – David Prun Aug 15 '12 at 23:50
  • 1
    @RandonP: That depends on what you are doing. If what you are trying to do is more or less "transactional" (e.g., writing something to disk, downloading something off the Internet), an `IntentService` will work well. If, OTOH, you are trying to do something that will run for an extended period of time (e.g., chat client with a service managing the thread that is listening on the socket for incoming chat messages), a regular `Service` with your own background thread is probably a better idea. – CommonsWare Aug 15 '12 at 23:51
  • Hey, please help me with this: [Broadcast receiver ANR](https://stackoverflow.com/questions/63735711/why-broadcast-receiver-is-causing-anr-on-only-huawei-devices) – Jazib Khan Sep 09 '20 at 15:04