好的,所以基本上你需要在後臺線程上運行你的查詢,並取消當前運行的查詢,如果用戶更改輸入並開始新的。 首先我們需要一個任務類,撫慰你的查詢:
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 –