【发布时间】:2014-08-22 10:26:28
【问题描述】:
我搜索了几个小时并尝试了 Stack Overflow 的所有答案,但没有解决我的问题。
我制作了 android 程序以完美运行以字节为单位下载数据。并用于在后台线程上工作的下载。我想显示一个进度对话框(只是旋转一个)。但我遇到了非常烦人的问题。我的下载大约需要 5 秒,但我的进度对话框没有显示或仅显示最后 1 秒。
这是我的 AsyncTask 代码。
public class ImageJSON extends AsyncTask<String, String, byte[]> {
private JSONObject jsonObject = new JSONObject();
private byte[] response;
private ProgressDialog pg;
private Context context;
public ImageJSON(Activity activity) {
pg = new ProgressDialog(activity);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pg.setMessage("Downloading, please wait.");
pg.show();
}
@Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
if (pg != null) {
pg.setProgress(Integer.parseInt(progress[0]));
}
}
protected void onPostExecute(byte[] result) {
if (pg.isShowing()) {
pg.dismiss();
}
}
@Override
protected byte[] doInBackground(String... params) {
HttpPost httpPost = new HttpPost("my file url....");
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
try {
jsonObject.put("imageId", params[0]);
StringEntity stringEntity = new StringEntity(jsonObject.toString());
httpPost.addHeader("Content_Type", "application/octet_stream");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity entity = httpResponse.getEntity();
if (entity!=null) {
response = EntityUtils.toByteArray(entity);
entity.consumeContent();
httpClient.getConnectionManager().shutdown();
}
} catch (JSONException|IOException e) {
e.printStackTrace();
}
return response;
}
我使用此代码从我的活动中调用它。
final ImageJSON imageTask = new ImageJSON(ReaderActivity.this);
byte[] response = imageTask.execute(imageId).get();
如果有人可以帮助我,在此先感谢。
【问题讨论】:
-
我们评论progressupdate方法时,试试看是否出现进度对话框?
-
不要调用 execute().get();它会阻止用户界面
-
取消注释 onProgressUpdate 没有帮助,但删除 get() 方法可以解决问题....thnx.
标签: android android-asynctask progressdialog