调用AsyncTask两次行为

时间:2013-07-25 16:37:06

标签: android android-asynctask

我正在尝试实施一个在您输入时自动搜索的搜索栏。

我的想法是让AsyncTask从服务器获取搜索数据,但我无法确定AsyncTask在使用它时的行为方式。

假设我有SearchAsyncTask

每次编辑文本字段时,我都会调用

new SearchAsyncTask().execute(params);

所以这是我的问题:这会是什么行为?我是否会启动许多不同的线程,这些线程都会返回并调用onPostExecute()?或者,如果另一个实例在仍在工作时被调用,那么第一个被调用的任务是否会在任务中停止?或者完全不同的东西?

如果我这样写怎么办?

SearchAsyncTask a = new SearchAsyncTask().execute(params);
...
a.execute(params2);
a.execute(params3);
...

2 个答案:

答案 0 :(得分:5)

我以同样的方式实现了我的应用搜索功能。我在用户输入时使用TextWatcher来构建搜索结果。我保留了我的AsyncTask的参考来实现这一点。我的AsyncTask声明:

SearchTask mySearchTask = null;  // declared at the base level of my activity

然后,在TextWatcher中,在每个字符输入上,我执行以下操作:

// s.toString() is the user input
if (s != null && !s.toString().equals("")) {

    // User has input some characters

    // check if the AsyncTask has not been initialised yet
    if (mySearchTask == null) {

        mySearchTask = new SearchTask(s.toString());

    } else {

        // AsyncTask is either running or has already finished, try cancel in any case
        mySearchTask.cancel(true);

        // prepare a new AsyncTask with the updated input            
        mySearchTask = new SearchTask(s.toString());

    }

    // execute the AsyncTask                
    mySearchTask.execute();

} else {

    // User has deleted the search string // Search box has the empty string "" now

    if (mySearchTask != null) {

        // cancel AsyncTask 
        mySearchTask.cancel(true);

    }

    // Clean up        

    // Clear the results list
    sResultsList.clear();

    // update the UI        
    sResultAdapter.notifyDataSetChanged();

}

答案 1 :(得分:0)

关于你的第二个问题,我相信你可以在这个网站上找到你的答案,例如here。 基本上,您只能执行一次AsyncTask的单个实例。 尝试执行两次相同的实例会引发错误。

编辑:如果您每次声明new SearchAsyncTask(),您都会收到大量回复并致电onPostExecute(),但不一定是正确的顺序。最好的方法是将AsyncTask存储在变量中,并在开始新的.cancel()方法之前使用{{1}}方法。