0
我正在为UAC中的项目编写一个小应用程序,并且在onClick事件后显示ProgressDialog时遇到问题。Android:按钮onClick在3秒后反应
基本上,当我的活动中调用onClick时,我启动一个AsyncTask并在onPreExecute中启动progressDialog,并在onPostExecute中再次解除它。
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<Recipe> recipes = null;
try {
ParsedElement x = new ParsedElement(v.getContext());
Object[] params = new Object[2];
params[0] = txtSearch.getText().toString();
params[1] = v;
recipes = (ArrayList<Recipe>) x.execute(params).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Intent switchToDisplayPage = new Intent(SearchActivity.this, UIGenerator.class);
Bundle params = new Bundle();
params.putParcelableArrayList("recipes", recipes);
switchToDisplayPage.putExtras(params);
startActivity(switchToDisplayPage);
}
});
我的问题是当点击“无”按钮约3秒发生。我已经观看了Android监视器,发现单击按钮时CPU使用率最高可达40%。
ProgressDialog progressDialog;
Context v;
public ParsedElement(Context v) {
this.v = v;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(v);
progressDialog.setTitle("Downloading");
progressDialog.setMessage("Recipes are loading...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
@Override
protected Object doInBackground(Object[] params) {
String searchString = (String) params[0];
View v = (View) params[1];
ArrayList<Recipe> recipes = new ArrayList<>();
try {
System.out.println(System.currentTimeMillis());
ArrayList<URL> single = new ArrayList<>();
single.add(new URL(Constants.baseSearchURL + searchString));
Document mainDocument = (Downloaders.getDocumentFromURL(single)).get(0);
Elements mainElements = mainDocument.select("div.img_wrap img[src]");
ArrayList<URL> urls = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
urls.add(new URL(Constants.baseSearchURL + searchString +
Constants.pageString + Integer.toString(i)));
}
ArrayList<Document> tempDocument = Downloaders.getDocumentFromURL(urls);
for (Document docu : tempDocument) {
Elements tempElement = docu.select("div.img_wrap img[src]");
for (Element a : tempElement) {
mainElements.add(a);
}
}
for (Element link : mainElements) {
recipes.add(new Recipe(link.attr("title"), link.attr("abs:src")));
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return recipes;
}
@Override
protected void onPostExecute(Object aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
在这种情况下,ProgressDialog不显示。我读了很多线索,基本上说“我在主线程中做得太多了”,显然在我的情况下我没有做任何重要的事情。
谢谢!