我在按钮的onclicklistener中定义了一个AsyncTask,一旦用户单击该按钮,理想情况下在asynctask下载时会显示进度对话框。
但是,进度对话框只是闪烁并在结果返回之前消失,并且当asynctask在后台运行时按钮会聚焦。
有人可以帮我弄清楚我在这里做错了什么吗?代码段:
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
((Button)findViewById(R.id.buttonLoginActivity)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AsyncTask<Void, Void, Void> downloadTask= new AsyncTask<Void, Void, Void>(){
@Override
protected Void doInBackground(Void... params) {
String data = Service.getSomeData();
context.getContentResolver.notifyChange("content://some_url");
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(progressDialog== null) return;
if(progressDialog!=null) {
progressDialog.dismiss();
progressDialog = null;
}
}
};
progressDialog.show();
downloadTask.execute();
try{
downloadTask.get();
}catch(Exception e){
e.printStackTrace();
return;
}
}
});
答案 0 :(得分:1)
请勿使用get()
downloadTask.get();
这是一个阻止通话。来自Docs
如果需要等待计算完成,然后检索其结果。
只需使用execute()
,然后根据onPostExecute()
答案 1 :(得分:0)
显示需要编写的onPreExecute
上的进度对话框,它将在UI线程上运行,而不是在后台运行(android 4)
我也会在new Handler().post(myAsynctaskcaller)
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}