2012-02-01 36 views
4

我在Service類中得到NetworkOnMainThreadException類,這本質上沒有意義,因爲服務是後臺進程,據我瞭解。NetworkOnMainThreadException服務中

在Service方法中,我正在調用靜態輔助方法來下載數據。我也使用DefaultHttpClient。

這是怎麼回事?

+0

你能展現更容易調查的代碼? – OleGG 2012-02-01 15:04:52

+0

查看我關於** ['NetworkOnMainThreadException']的帖子(http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html)**。它解釋了爲什麼會發生這種情況 – 2012-08-02 15:16:28

回答

5

onStartCommand()Service的UI線程上運行。嘗試使用IntentService,或在ServiceHandler/RunnableAsyncTask)中使用任何其他線程方法。

+0

它不允許在服務中調用AsyncTask,因爲它應該從主步驟執行,對嗎? – bgplaya 2014-03-31 16:06:57

+0

@bgplaya你絕對可以在'Service'中使用'AsyncTask'。正如我上面所說的,常規的「服務」在主(UI)線程上運行。 – 2014-03-31 16:20:02

+0

我應該檢查一下我的代碼,但好像我在'Service'中使用'AsyncTask'出現了問題:或許我只是在'onStartCommand() – bgplaya 2014-03-31 16:39:46

0

服務回調都在主線程上運行,也就是UI線程。如果你想做後臺工作,可以啓動一個Thread,或者使用IntentService的onHandleIntent(Intent i)。

0

我只是用這個解決此問題:

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

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

    return START_STICKY; 
} 

RefreshDBAsync在每5分鐘進行請求到服務器

相關問題