问题
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?
回答1:
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
).
回答2:
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).
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/9098085/networkonmainthreadexception-in-service