【问题标题】:Calling an AsyncTask twice behavior调用 AsyncTask 两次行为
【发布时间】:2013-07-25 16:37:06
【问题描述】:

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

我的想法是拥有一个从服务器获取搜索数据的AsyncTask,但我无法确定AsyncTask 在我使用它时的表现如何。

假设我有SearchAsyncTask

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

new SearchAsyncTask().execute(params);

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

如果我这样写呢?

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

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    我以同样的方式实现了我的应用程序的搜索功能。我使用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();
    
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这并不能真正回答问题。在问题的第一部分,他没有执行相同的实例。但它确实回答了第二个问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多