2011-01-28 52 views
1

Android開發和Java一般都很新,所以請原諒任何業餘的無知和缺乏術語。防止互聯網訪問方法延遲吐司

我正在開發一個Android應用程序,該應用程序使用基於http://www.spartanjava.com/2009/get-a-web-page-programatically-from-android/處可用代碼的方法將網頁作爲字符串獲取。

這需要少量但明顯的時間,但工作正常。它通過按下UI中的按鈕來觸發。由於應用程序在獲取數據時沒有響應,因此我有一個敬酒,旨在在用戶發生之前發出警告。

這裏基本上正在做什麼(而不是實際的代碼,只是舉例):

public void buttonPressed(View view) 
{ 
    Toast.makeText(this, "Getting Data!", Toast.LENGTH_LONG).show(); 

    //See the page linked above for the code in this function! 
    String page = getPage("http://www.google.com/"); 

    Toast.makeText(this, "Data Retrieved!", Toast.LENGTH_LONG).show(); 
} 

不幸的是,「獲取數據」舉杯似乎只有GETPAGE方法完成後出現,出現的很簡單然後被「Data Retrieved」吐司覆蓋。

如何避免這種情況,使得「獲取數據」toast出現,然後getPage方法運行,然後在方法終止時出現「Data Retrieved」toast?

任何建議將不勝感激。我想到的解決方案涉及某種線索或同步的,但甚至不知道從哪裏開始尋找一個合適的教程...

格雷格

回答

2

正確使用AsyncTask類的,解決你的問題:

通知onPreExecuteonPostExecute在您獲取頁面之前/之後調用的方法。

public class HomeActivity extends Activity { 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.home); 
    } 
    public void buttonPressed(View view) { 
     new MyAsyncTask(this).execute(new String[] {"http://google.com/"}); 
    } 
    private class MyAsyncTask extends AsyncTask<String, Void, String> { 
     private Context context; 
     public MyAsyncTask(Context context) { 
      this.context = context; 
     } 
     @Override 
     protected String doInBackground(String... params) { 
      String page = getPage(params[0]); 
        //do any more work here that may take some time- like loading remote data from a web server, etc 
      return page; 
     } 
     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 
      Toast.makeText(context, "Data Retrieved: " + result, Toast.LENGTH_LONG).show(); 
     } 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      Toast.makeText(context, "Getting Data!", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 
+0

另請注意,doInBackground()在後臺線程中運行,並且不能從UI(線程)中訪問東西即:它不能嘗試發送Toast – 2011-01-28 15:51:51

1

你不應該執行長時間運行(即網絡或磁盤I/O)在UI線程中的操作。您應該使用AsyncTaskThread/Handler組合。

這裏有一些鏈接:

+0

感謝指針 - 我一直在試圖解決AsyncTask過去幾個小時,但似乎無法得到它的工作......或者至少,我設法得到*東西*工作,但它不能解決敬酒的原始問題。 – Greg 2011-01-28 14:10:49