NetworkOnMainThreadException in Service

╄→尐↘猪︶ㄣ 提交于 2019-12-01 20:28:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!