我是Android新手,我試圖開發包含搜索功能的文件瀏覽器。我使用的遞歸搜索功能可以在具有幾個子文件夾和文件的文件夾中正常工作,但由於某些原因,它的EXTREMELY SLOW很慢,並且可能會在具有大量子文件夾和文件的文件夾中「強制關閉」,因爲內存不足。我通過創建將放置結果的ArrayList來完成搜索,然後調用將填充列表的遞歸函數。 「路徑」參數是搜索將從其開始的文件,「查詢」是搜索查詢。在android中創建一個快速文件搜索功能
ArrayList<File> result = new ArrayList<File>();
fileSearch(path, query, result);
這是遞歸函數的樣子:
private void fileSearch(File dir, String query, ArrayList<File> res) {
if (dir.getName().toLowerCase().contains(query.toLowerCase()))
res.add(dir);
if (dir.isDirectory() && !dir.isHidden()) {
if (dir.list() != null) {
for (File item : dir.listFiles()) {
fileSearch(item, query, res);
}
}
}
}
如果有人能指出我進行更快和/或更有效的文件搜索的一種方式,我真的很感激。
編輯:
這是我試圖做的AsyncTask工作:
private class Search extends AsyncTask<File, Integer, Void> {
String query;
ArrayList<File> result = new ArrayList<File>();
public Search(String query){
this.query = query;
setTitle("Searching");
}
@Override
protected Void doInBackground(File... item) {
int count = item.length;
for (int i = 0; i < count; i++) {
fileSearch(item[i], query, result);
publishProgress((int) ((i/(float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
setProgress(progress[0]);
}
protected void onPostExecute() {
searchResults = new ListItemDetails[result.size()];
for (int i = 0; i < result.size(); i++) {
File temp = result.get(i);
if (temp.isDirectory())
searchResults[i] = new ListItemDetails(temp.getAbsolutePath(),
R.drawable.folder, temp.lastModified(), temp.length());
else {
String ext;
if (temp.getName().lastIndexOf('.') == -1)
ext = "";
else
ext = temp.getName().substring(
temp.getName().lastIndexOf('.'));
searchResults[i] = new ListItemDetails(temp.getAbsolutePath(),
getIcon(ext), temp.lastModified(), temp.length());
}
}
finishSearch();
}
}
public void finishSearch() {
Intent intent = new Intent(this, SearchResults.class);
startActivity(intent);
}
到finishSearch()的調用,這樣我可以創造的意圖,表明在其他活動的結果。任何想法,建議,提示?在此先感謝
強制關閉可能是由於執行上的主線程的代碼,使用的AsyncTask – nandeesh 2012-08-11 19:23:20
可以爲用戶提供教程或有關的AsyncTask的一些信息鏈接? – kiko283 2012-08-11 21:08:49
在這裏檢查http://developer.android.com/reference/android/os/AsyncTask.html – nandeesh 2012-08-11 21:12:23