0

I added some network socket code in the onStartCommand() method of my implementation of Service class. But I got NetworkOnMainThread exception. Some folks suggested that a Service runs on UI thread, which makes sense to me. However the doc says Service is intended for long running operations, this is confusing since how could a long-running service not blocking UI if it runs on UI thread?

flx
  • 14,146
  • 11
  • 55
  • 70
wizoleliam
  • 83
  • 3
  • 13

1 Answers1

3

You still have to spawn a Thread into background for IO or use a IntentService which does that for you.

See the Service as a process running on the UI Thread, although it has no UI itself.

flx
  • 14,146
  • 11
  • 55
  • 70
  • Thank you for the answer @flx, but IntentService will shut itself down once work is done. I wish to maintain a persistent socket which will keep connected as long as the app is running. Do you have any suggestions? – wizoleliam Feb 24 '14 at 07:18
  • Spawn a `Thread` from `Service` and maintain it from there. But make sure to listen to any android life-cycle changes for the service. You may want to read something about a `WakeLock`. – flx Feb 24 '14 at 07:35
  • then what's the difference from spawning a thread from main UI thread? for example, say the my activity get destroyed(in case of screen rotation) or in event of an incoming call(activity goes into background), what's the difference between spawning the thread in main ui thread and in the service? Thanks – wizoleliam Feb 24 '14 at 07:48
  • The Thread spawned from an Activity might die on e.g. orientation changes. – flx Feb 24 '14 at 07:50
  • why? if Service and main UI runs on the same thread. Thank you for your patience. – wizoleliam Feb 24 '14 at 07:53
  • because that's how the system was designed. – flx Feb 24 '14 at 07:56
  • do you mind accepting this answer, or do you have any issue with it? – flx Feb 28 '14 at 03:27