2015-10-18 24 views
-4

我不知道如何使用线程;我只是想学习如何制作一个简单的android程序,但我试图使用一个API,我得到了一个N​​etworkOnMainThread异常。 我读到这意味着我需要将我的httpUrlConnection放在后台线程中(doInBackground显然可能会有所帮助),但我在互联网上遇到了教程问题。如何使用doInBackground摆脱NetworkOnMainThread异常的

我有正确的方法现在被称为getResults它接受一个字符串,并返回一个列表。有没有一种简单的方法来适应doInBackground,以便我不必改变我的方法?

的如何这样做使用doInBackground(或任何其它方法)的一个例子将是很好。

+2

见Android的指南网络运营,它说明了在哪里放,使网络调用的代码:http://developer.android.com/training/basics/network- OPS/connecting.html – ESala

回答

0

有关于在网络这些问题的信息很多,它只是谷歌。

通常当你想运行的网络请求,你应该做它在另一个线程,而不是你的UI线程。 AsyncTask是实现这一目标的更常用方法之一。

一个例子来自Android Developers

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
protected Long doInBackground(URL... urls) { 
    //this is the place for the long background work 
    int count = urls.length; 
    long totalSize = 0; 
    for (int i = 0; i < count; i++) { 
     totalSize += Downloader.downloadFile(urls[i]); 
     publishProgress((int) ((i/(float) count) * 100)); 
     // Escape early if cancel() is called 
     if (isCancelled()) break; 
    } 
    return totalSize; 
} 

protected void onProgressUpdate(Integer... progress) { 
    //If needed here you can update the UI about the progress. 
} 

protected void onPostExecute(Long result) { 
    //Here you can update the UI 
} 

}

你也应该阅读Connecting to the Network为Darkean评论。

这也很推荐Android background processing with Handlers, AsyncTask and Loaders - Tutorial