NetworkOnMainThreadException in Service

3.6k views Asked by At

I'm getting a NetworkOnMainThreadException in my Service class, which by nature doesn't make sense, because Services are background processes as far as I understand.

In the Service method, I'm making a call to a static helper method to download data. I'm using the DefaultHttpClient as well.

What's going on here?

4

There are 4 answers

3
Paul Burke On BEST ANSWER

onStartCommand() runs on the UI thread in a Service. Try using IntentService, or alternatively use any other threading method in the Service (Handler/Runnable, AsyncTask).

0
SimonVT On

Service callbacks all run on the main thread, aka the UI thread. If you wish to do background work, either start a Thread, or use IntentService's onHandleIntent(Intent i).

0
hector6872 On

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

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

0
J.P On

i just resolve this problem by using this :

public int onStartCommand(Intent intent, int flags, int startId) {

    RefreshDBAsync task = new RefreshDBAsync(this);
    task.execute();

    return START_STICKY;
}

RefreshDBAsync is making request to a server at every 5 minutes