如何在Java中实现javascript setTimeout函数
我目前正在尝试在 android 中集成实时搜索功能。我使用自定义的自动完成小部件。小部件本身为我提供了一个阈值,仅在输入一定数量的字符后才开始查询。但我还想要的是,查询仅在用户停止输入 2 秒后才开始。
当我使用 AsyncTask
加载内容时,我尝试通过在开始时调用 Thread.sleep() 来阻止 doInBackground
函数。如果用户继续输入,程序将处理现有任务,取消它并开始一项新任务。这是我的想法。但它并不完全按照我预期的方式工作。有时,即使用户仍在打字,它也会发出查询,有时,在用户停止打字后,查询会被取消。
您对此有什么想法或者更好的方法来解决这个问题吗?
以下是代码片段:
1.文本更改时调用的函数:
public void afterTextChanged(Editable s) {
if(mWidget.enoughToFilter()) {
if(mTask != null && mTask.getStatus() != Status.FINISHED) {
mTask.cancel(true);
}
mTask = new KeywordSearchLoader(mActivity,
mItems);
mTask.execute(s.toString());
}
}
2. doInBrackground
try {
Thread.sleep(Properties.ASYNC_SEARCH_DELAY);
} catch (InterruptedException e) {
Log.e(TAG, "the process was interrupted while sleeping");
Log.w(TAG, e);
}
谢谢 菲尔
I am currently trying to integrate a live search functionality in android. I use a customized Autocomplete widget. The widget itself provides me with a threshold to only start a query after a certain amount of characters have been typed in. But what I also want is that a query only starts, say if a user has stopped typing for 2 seconds.
As I load my contents with a AsyncTask
I tried blocking the doInBackground
function by calling Thread.sleep() right at the beginning. If the user would then continue typing the program would look after an existing task, cancel it and start a new one. This was my idea. But it doesn't quite work the way I expected. Sometimes it sends out queries even if the user is still typing, sometimes queries are canceled after the users stopped typing.
Do you have any ideas on this or maybe a better way to solve this?
Here are the code snippets:
1. The function that is called on text changes:
public void afterTextChanged(Editable s) {
if(mWidget.enoughToFilter()) {
if(mTask != null && mTask.getStatus() != Status.FINISHED) {
mTask.cancel(true);
}
mTask = new KeywordSearchLoader(mActivity,
mItems);
mTask.execute(s.toString());
}
}
2. doInBrackground
try {
Thread.sleep(Properties.ASYNC_SEARCH_DELAY);
} catch (InterruptedException e) {
Log.e(TAG, "the process was interrupted while sleeping");
Log.w(TAG, e);
}
Thanks
Phil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个 Handler 并使用
.postDelayed(..)
在延迟一段时间后运行后台任务。如果用户按下该键,则调用
handler.removeCallback(..)
,然后再次.postDelayed(..)
添加新的延迟回调。Create a
Handler
and use.postDelayed(..)
to run a background task after some delay.If user presses the key then call
handler.removeCallback(..)
and then again.postDelayed(..)
to add a new delayed callback.