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不顯示。我讀了很多線索,基本上說「我在主線程中做得太多了」,顯然在我的情況下我沒有做任何重要的事情。
謝謝!