2

我以某种方式使用 AsyncTask 在 android 中实现了增量搜索。在增量搜索中,为编辑文本中输入的每个字符调用 API 以从服务器获取建议。例如,

User types a -> API is called.
User types ab -> API is called.
User types abc -> API is called. 

这分别对 a、ab 和 abc 进行了三个 API 调用。如果用户仍在键入,则所有先前的请求(例如 a 和 ab 的请求)将被取消,最后一个请求 (abc) 将被提供,以避免延迟。

现在我想使用 Volley 库来实现它以获得更好的性能。任何人都可以帮助我如何使用 volley 来实现此功能,特别是取消所有先前请求的机制并仅提供最后一个请求以从服务器获取建议。

注意:我找不到这就是为什么在这里发布它。请指导我,因为我是 android 新手,真的需要回答。

4

1 回答 1

1

首先你需要实现一个TextWatcher来监听编辑文本的变化。根据更改文本的要求,您取消并将请求添加到队列。

private RequestQueue queue = VolleyUtils.getRequestQueue();


private static final String VOLLEY_TAG = "VT";
private EditText editText;
...

 TextWatcher textChangedListener = new TextWatcher() {

          @Override
          public void afterTextChanged(Editable s) {}

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (s.length() != 0) {
                // first cancel the current request with that tag
                queue.cancelAll(VOLLEY_TAG);
                // and then add a new one to queue
                StringRequest stringRequest = 
                     new StringRequest("http://blabla/servlet?param=" + s, 
                     new Listener<String>() {
                       // request callbacks
                     };
                stringRequest.setTag(VOLLEY_TAG);
                queue.add(stringRequest);
            } 
        }
  };

editText.addTextChangedListener(textChangedListener);

请记住,这种设计会吞噬带宽。更好的方法是Handler.post()在触发请求之前等待几秒钟。

于 2015-05-15T05:21:23.760 回答