使用异步任务怎么样,读取文件或下载东西,需要用户等待的时间,您必须考虑为此目的使用异步任务,
1:来自我们的开发者参考:
AsyncTask 可以正确和轻松地使用 UI 线程。此类允许在 UI 线程上执行后台操作并发布结果,而无需操作线程和/或处理程序。http://developer.android.com/reference/android/os/AsyncTask.html
异步任务由 3 个通用类型定义,称为 Params、Progress 和 Result,以及 4 个步骤,称为 onPreExecute、doInBackground、onProgressUpdate 和 onPostExecute。
2:所以你可以包括一个异步任务类:
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 方法中调用,方法是调用它的 execute 方法并将参数传递给它:
new DoBackgroundTask().execute(URL);
3:最后,这里还有一个关于 AsyncTasks 的非常好的教程,http: //www.vogella.com/articles/AndroidBackgroundProcessing/article.html