Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : using the network in a service

Making a call to a REST WebService in a Service class of my Android app create the NetworkOnMainThreadException.

I understand why this exception is raised in an Activity : fetching something over the network synchronously is an extremely bad practice but I am surprised to see that same error in a Service Class. So my question is :

-In this specific case, should I use StrictMode.setThreadPolicy() to allow this call. (And for those that read this because they have encountered this error in an activity, don't use StrictMode to hide this error, use an AsyncTask)

-or should I use an AsyncTask ? And in that case, what is the issue here ? Isn't the service on a thread separated from the Activity's one ?

like image 376
Teovald Avatar asked Aug 08 '12 23:08

Teovald


1 Answers

Even though Service is intended for background processing they run in the main thread .

A short quote from the documentation:

Caution: A services runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.

The 'background processing' means that service has no user interface, it can run even if the user isn't directly interacting with the application. But all the background processing still happens in the main thread by default.

So, how to solve it and get rid of the exception? As the documentation suggests you have to use a background thread. In your service you can use AsyncTask or create threads directly. But I guess IntentService might be the most suitable in your case. IntentService processes requests in the background thread (so that's the kind of service you were looking for).

like image 183
Tomik Avatar answered Oct 21 '22 02:10

Tomik