Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 563
Vadim Peretokin Avatar asked Oct 08 '22 04:10

Vadim Peretokin


1 Answers

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.

like image 110
AdamK Avatar answered Oct 12 '22 10:10

AdamK