好的,所以基本上你需要在后台线程上运行你的查询,并取消当前运行的查询,如果用户更改输入并开始新的。 首先我们需要一个任务类,抚慰你的查询:
class CancelableTask implements Callable<Void> {
//need this to know, if the task was canceled
private Future<Void> myFuture;
public void setMyFuture(Future<Void> myFuture) {
this.myFuture = myFuture;
}
@Override
public Void call() throws Exception {
//we run a loop until the query is finished or task was canceled
while (!this.myFuture.isCancelled() && !myQuery.isFinished()) {
//the step should be small enough to fast detect task cancellation but big enough to avoid too much overhead
myQuery.performQueryStep();
}
if(!this.myFuture.isCancelled()){
//query is finished and task wasn't canceled, so we should update UI now
updateUIOnUIThread(myQuery.result());
}
return null;
}
}
现在你需要在你的活动的地方创建ExecutorService
:
//1 Thread should be enough, you could use 2 Threads if your query-step is quite long and you want to start the following query faster
private ExecutorService executor = Executors.newSingleThreadExecutor();
现在我们可以用executor
运行的任务。用户更改输入后应立即调用此代码。它应该在UI线程上调用以避免设置问题currentTaskFuture
:
//check if need to cancel the currentTask
if(currentTaskFuture != null && !currentTaskFuture.isDone()){
currentTaskFuture.cancel(false);
}
CancelableTask task = new CancelableTask();
//submit the task
Future<Void> future = executor.submit(task);
task.setMyFuture(future);
//set current task's future so we can cancel it if needed
currentTaskFuture = future;
什么是您的用户界面(手机或网络)? –
你基本上可以使用任务来更新已经过滤的结果的队列,然后根据这些进行细化(而你的“主要搜索者”只根据最新的查询在队列中放置新的队列) – Rogue
@ShlomiHaver它是移动的。 Android –