NetworkOnMainThreadException in Service

2019-02-24 04:10发布

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条回答
Explosion°爆炸
2楼-- · 2019-02-24 05:02

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

查看更多
Ridiculous、
3楼-- · 2019-02-24 05:10

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).

查看更多
Anthone
4楼-- · 2019-02-24 05:10

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

查看更多
劳资没心,怎么记你
5楼-- · 2019-02-24 05:13

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).

查看更多
登录 后发表回答