调用AsyncTask两次行为

Mic*_*yle 3 android android-asynctask

我正在尝试实现一个在您键入时自动搜索的搜索栏.

我的想法是AsyncTask从服务器获取搜索数据,但我无法确定AsyncTask使用它的确切行为.

让我说我有SearchAsyncTask.

每次编辑文本字段时我都会打电话

new SearchAsyncTask().execute(params);
Run Code Online (Sandbox Code Playgroud)

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

如果我这样写的怎么办?

SearchAsyncTask a = new SearchAsyncTask().execute(params);
...
a.execute(params2);
a.execute(params3);
...
Run Code Online (Sandbox Code Playgroud)

Vik*_*ram 5

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

SearchTask mySearchTask = null;  // declared at the base level of my activity
Run Code Online (Sandbox Code Playgroud)

然后,在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();

}
Run Code Online (Sandbox Code Playgroud)