我用谷歌搜索了几个小时并尝试了Stack Overflow的所有答案,但没有解决我的问题。
我让android程序以字节为单位下载完美的数据。并下载工作在后台线程。我想显示一个进度对话框(jus Spinning one)。但我真的很讨厌问题。我的下载大约需要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();
如果有人可以帮助我,请提前致谢。
答案 0 :(得分:3)
您不希望使用get()
,因为它仍会冻结您的UI线程,从而否定使用AsyncTask
的意义。您可能希望实施onPostExecute
以便正确返回结果。
答案 1 :(得分:0)
试试这个 -
public ImageJSON(Activity activity) {
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(ReaderActivity.this);
pg.setMessage("Downloading, please wait.");
pg.show();
}
答案 2 :(得分:0)
您忘记在onPreExecute方法中初始化您的进度对话
@Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(pass_context_here);
pg.setMessage("Downloading, please wait.");
pg.show();
}
答案 3 :(得分:0)
更改此
public ImageJSON(Context ctx) {
this.context = ctx;
}
现在在onPreExecute()
方法中使用此
@Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(context);
pg.setMessage("Downloading, please wait.");
pg.show();
}
您在ProgressDialog
类中初始化ImageJSON
,阻止您的UI线程意味着将其冻结。因此需要参考上下文在onPreExecute()
方法中初始化它。