2011-06-22 55 views
1

我遇到了一個問題,我確信它解決起來非常簡單,但我仍然開始開發應用程序,所以我認爲你可以幫助我。 我收到了一個應用程序,裏面有一個貨幣換算器,當我按下按鈕以獲得轉換時,它會凍結它從互聯網獲取數據並在數秒後恢復生命。這裏是代碼:當從互聯網獲取數據時,應用程序凍結

public void capturaConversao(String m1, String m2) throws ClientProtocolException, IOException { 
     BufferedReader resp = null; 
     endereco = "http://download.finance.yahoo.com/d/quotes.csv?s=" + m1 
       + m2 + "=X&f=sl1d1t1ba&e=.csv"; 
     try { 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet method = new HttpGet(endereco); 
      HttpResponse statusCode = client.execute(method); 
      resp = new BufferedReader(new InputStreamReader(statusCode 
        .getEntity().getContent())); 
      StringBuffer sb = new StringBuffer(""); 
      String line = ""; 
      while ((line = resp.readLine()) != null) { 
       sb.append(line); 
      } 
      resp.close(); 
      String result = sb.toString(); 
      String[] values = result.split(","); 
      conversion = values[1]; 
      nextstep++; 

     } finally { 
      if (resp != null) { 
       try { 
        resp.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        Toast.makeText(getBaseContext(), "Não foi possível se conectar à internet.", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     } 
    } 

回答

1

AsyncTask是幾乎所有UI線程困境的解決方案。 :) 這是一個簡短的tutorial

+0

謝謝!這非常容易設置和學習!適合我的應用程序!我真的需要了解線程工作,但現在AsyncTask做了工作! – Thpramos

0

你可能會從UI線程調用這個,你不應該這樣做。它會使UI鎖定,因爲UI線程正忙於連接到Internet。 Here's a tutorial for making such a call

+0

Thaanks爲輔導人!我現在投票選擇了其他的原因,AsyncTask將工作做得很好......但是肯定我必須學習線程的工作方式,本教程是一個非常好的開始! – Thpramos

0

您的UI線程的可用週期正在被HTTP操作佔用。與無論是ThreadAsyncTask

0

是的,我也同意一起去的AsyncTask解決方案獨立出來,當它被稱爲無痛線程處理,用戶需要不操心線程管理。

對於你的情況,只是調用capturaConversao()方法中doInBackground()(即做所有的數據獲取doInBackground方法中,從網絡操作)和調用onPostExecute(內部的顯示方法)(即做所有顯示操作,如顯示在列表視圖或文本視圖中獲取的值)。

相關問題