Android: using the network in the service

When making a REST WebService call in the service class of my Android application, NetworkOnMainThreadException .

I understand why this exception occurs in Activity: getting something over the network synchronously is a very bad practice, but I am surprised to see the same error in the service class. So my question is:

- In this particular case, I should use StrictMode.setThreadPolicy() to resolve this call. (And for those who read this because they encountered this error in action, do not use StrictMode to hide this error, use AsyncTask)

- or should I use AsyncTask? And in this case, what is the problem? Isn't the service disconnected from one action?

+7
source share
1 answer

Even if Service is intended for background processing, they are launched in the main thread .

A short quote from the documentation :

Warning. Services run in the same process as the application in which it is declared, and in the main thread of this application, by default. Thus, if your service performs intensive or blocking operations when a user interacts with activity from the same application, the service slows down. In order not to affect application performance, you must start a new thread inside the service.

"Background processing" means that the service does not have a user interface, it can work even if the user does not interact directly with the application. But all background processing still happens in the main thread by default.

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

+12
source

All Articles