NetworkOnMainThreadException in the service

I get a NetworkOnMainThreadException in my Service class, which by its nature does not make sense, because Services are background processes, as I understand it.

In the "Service" method, I refer to the static helper method for loading data. I also use DefaultHttpClient.

What's going on here?

+4
source share
4 answers

onStartCommand() runs on the user interface thread in Service . Try using the IntentService or, alternatively, using any other streaming method in the Service ( Handler / Runnable , AsyncTask ).

+5
source

Service callbacks are executed in the main thread, otherwise as a user interface thread. If you want to perform a wallpaper, run Thread or use IntentService onHandleIntent (Intent i).

0
source

An exception that occurs when an application attempts to perform network operations in the main thread.

This is only for applications targeting the Honeycomb SDK or higher. Allowed to use applications that focus on earlier versions of the SDK. Networks in their main event loop threads, but this is highly discouraged.

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

0
source

I just solve this problem using this:

 public int onStartCommand(Intent intent, int flags, int startId) { RefreshDBAsync task = new RefreshDBAsync(this); task.execute(); return START_STICKY; } 

RefreshDBAsync makes a server request every 5 minutes

0
source

Source: https://habr.com/ru/post/1394199/


All Articles