早安, 我的Android应用程序上有一个按钮,通过AsyncTask在网络上启动搜索(通过谷歌端点)。我的问题是,在AsyncTask完成之前,该按钮不会“取消”,这可能需要几秒钟。当互联网连接速度很慢时,这甚至会使应用程序崩溃,在任何情况下,应用程序都会完全停滞,直到完成AsyncTask。现在使用AsyncTask的原因正是为了消除这个问题,所以我真的不知道会发生什么!
这是OnClickListener:
SearchListener = new OnClickListener() {
@Override
public void onClick(View v) {
String cname=TextCourse.getText().toString();
if (!cname.isEmpty()){
try {
CollectionResponseWine listavini= new QueryWinesTask(messageEndpoint,cname,5).execute().get();
} catch (InterruptedException e) {
showDialog("Errore ricerca");
e.printStackTrace();
} catch (ExecutionException e) {
showDialog("Errore ricerca");
e.printStackTrace();
}
} else{
showDialog("Inserisci un piatto");
}
}
};
这里是被调用的AsyncTask:
private class QueryWinesTask
extends AsyncTask<Void, Void, CollectionResponseWine> {
Exception exceptionThrown = null;
MessageEndpoint messageEndpoint;
String cname;
Integer limit;
public QueryWinesTask(MessageEndpoint messageEndpoint, String cname, Integer limit) {
this.messageEndpoint = messageEndpoint;
this.cname=cname;
this.limit=limit;
}
@Override
protected CollectionResponseWine doInBackground(Void... params) {
try {
CollectionResponseWine wines = messageEndpoint.listwines().setCoursename(cname).setLimit(limit).execute();
return wines;
} catch (IOException e) {
exceptionThrown = e;
return null;
//Handle exception in PostExecute
}
}
protected void onPostExecute(CollectionResponseWine wines) {
// Check if exception was thrown
if (exceptionThrown != null) {
Log.e(RegisterActivity.class.getName(),
"Exception when listing Messages", exceptionThrown);
showDialog("Non ci sono vini associati al tuo piatto. Aggiungine uno!");
}
else {
messageView.setText("Vini piu' votati per " +
cname + ":\n\n");
for(Wine wine : wines.getItems()) {
messageView.append(wine.getName() + " (" + wine.getScore() + ")\n");
}
}
}
}
答案 0 :(得分:3)
...execute().get()
正在阻止。它使UI线程等待Task完成。
不要get()
。使用onPostExecute()
获取任务的结果(wines
)并更新用户界面。