實現android非同步呼叫WEB API的方法

來源:互聯網
上載者:User

在一般應用中我們很多時候都會遇到利用網路請求實現和客戶互動的操作,由於網路的請求需要或長或短的時間等待,所以我們一般會把顯示介面和網路請求取得資料的操作放在不同的線程上操作,把介面的操作放在主線程,而從網路取得資料的操作就放在另外一個子線程中操作,網上說明這個實現方法的資料過於貧乏,所以我把實驗代碼貼出來

下面的類使用一個單獨的線程從主介面線程的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);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.