在一般應用中我們很多時候都會遇到利用網路請求實現和客戶互動的操作,由於網路的請求需要或長或短的時間等待,所以我們一般會把顯示介面和網路請求取得資料的操作放在不同的線程上操作,把介面的操作放在主線程,而從網路取得資料的操作就放在另外一個子線程中操作,網上說明這個實現方法的資料過於貧乏,所以我把實驗代碼貼出來
下面的類使用一個單獨的線程從主介面線程的HTTP調用Android的AsyncTask。事實上,在較新版本的Android上你是無法在主線程上調用的,你會得到一個異常 android.os.networkonmainthreadexception
public class ApiCall extends AsyncTask { private String result; protected Long doInBackground(URL... urls) {int count = urls.length; long totalSize = 0; StringBuilder resultBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { try { // Read all the text returned by the server InputStreamReader reader = new InputStreamReader(urls[i].openStream()); BufferedReader in = new BufferedReader(reader); String resultPiece; while ((resultPiece = in.readLine()) != null) { resultBuilder.append(resultPiece); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // if cancel() is called, leave the loop early if (isCancelled()) { break; } } // save the result this.result = resultBuilder.toString(); return totalSize; } protected void onProgressUpdate(Integer... progress) { // update progress here }// called after doInBackground finishes protected void onPostExecute(Long result) { Log.v("result, yay!", this.result); }}
調用方法很簡單,如下:
URL url = null;try { url = new URL("http://search.twitter.com/search.json?q=@justinjmcc");} catch (MalformedURLException e) { e.printStackTrace();}new ApiCall().execute(url);