配置AsyncTask以在自动完成搜索中使用的最佳方法

时间:2016-01-09 00:41:07

标签: android performance android-asynctask

我在SearchView的onQueryTextChange方法中调用AsyncTask并在列表中显示结果。搜索有效,但如果用户在搜索视图中快速输入,则偶尔会挂起一秒钟。我想进一步优化这种方法。由于它是一个自动完成搜索,当用户开始输入时,几个AsyncTasks排队等待执行。但我只对最后一次搜索请求感兴趣。

目前,我正在做这样的事情

if (myAsyncTask != null)
    myAsyncTask.cancel(true);

   myAsyncTask = new MyAsyncTask(context,URL);

有更好的方法吗?如果可能的话,我想做这样的事情

myAsyncTask.executeOnExecutor(new OptimizedExectionerService);

OptimizedExectionerService类应该取消池中的所有挂起和运行任务,并且只处理最后发出的请求。

1 个答案:

答案 0 :(得分:2)

使用具有合理延迟的处理程序(处理在edittext中的输入)。

private static final int SEARCH_DELAY = 500;
private Handler mHandler = new Handler();
private SearchRunnable executeSearch = new SearchRunnable();

private queueSearch(String term) {
    // Remove any previous searches
    mHandler.removeCallbacks(executeSearch);

    // Set the search term for the runnable
    executeSearch.setSearchTerm(term);

    // Schedule the search in half a second
    mHandler.postDelayed(executeSearch, SEARCH_DELAY);
}

private class SearchRunnable implements Runnable {
    String searchTerm = null;

    public void setSearchTerm(String term) {
        searchTerm = term;
    }

    @Override
    public void run() {
         //Execute Search here
         new MyAsyncTask(context, searchTerm);
    }
};