如何使用異步任務,讀取文件或下載的東西,需要需要用戶等待的時間,你必須考慮使用異步任務用於此目的,
1:從開發人員參考我們有: AsyncTask使適當和簡單的使用UI線程。該類允許執行後臺操作並在UI線程上發佈結果,而無需操縱線程和/或處理程序。 http://developer.android.com/reference/android/os/AsyncTask.html
異步任務由3個泛型類型定義,稱爲Params,Progress和Result,以及4個步驟,分別稱爲onPreExecute,doInBackground,onProgressUpdate和onPostExecute。
2:所以,你可能包括一個異步任務類爲:
new DoBackgroundTask().execute(URL);
:
class DoBackgroundTask extends AsyncTask<URL, Void, ArrayList> {
/*
URL is the file directory or URL to be fetched, remember we can pass an array of URLs,
Void is simple void for the progress parameter, you may change it to Integer or Double if you also want to do something on progress,
Arraylist is the type of object returned by doInBackground() method.
*/
@Override
protected ArrayList doInBackground(URL... url) {
//Do your background work here
//i.e. fetch your file list here
return fileList; // return your fileList as an ArrayList
}
protected void onPostExecute(ArrayList result) {
//Do updates on GUI here
//i.e. fetch your file list from result and show on GUI
}
@Override
protected void onProgressUpdate(Integer... values) {
// Do something on progress update
}
}
//Meanwhile, you may show a progressbar while the files load, or are fetched.
這的AsyncTask可以從你onCreate方法通過調用其執行方法並傳遞參數給它叫
3:,最後,還有關於這裏AsyncTasks一個非常好的教程,http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
在背景上運行它,然後加載可能有太多 – Trikaldarshi
@Photon我也嘗試使用相同的線程,但相反,造成不必要的複雜性,沒有結果 – user2714061