Vadim Peretokin
Vadim Peretokin

Reputation: 2846

android.os.NetworkOnMainThreadException in a Service in a separate process

On ICS, I'm getting an android.os.NetworkOnMainThreadException error when using UrlConnection - even though I'm making this request in a Service that runs on it's own process, and was called asyncronously to be done via Messenger.

Changing the StrictPolicy had no effect, I still get the error.

What can I do?

edit: this Service runs in a separate process - has a different pid and everything.

Upvotes: 5

Views: 3737

Answers (2)

Kayhan Asghari
Kayhan Asghari

Reputation: 2854

Do the network stuff in a Thread there. this exception is thrown to prevent some problems, like the UI freezing (because of the network job, that may take time.)

Upvotes: 0

AdamK
AdamK

Reputation: 21399

Services still run on the main thread, as per the the documentation:

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

Therefore for long running tasks (such as using a UrlConnection) you should either use something like an IntentService or spawn a new Thread yourself.

Upvotes: 4

Related Questions