我正在做一个Android应用程序,它具有在我点击imageview时下载图像的功能。我已经使用Asynctask开始一个新的线程下载。但是,从不调用onProgressUpdate和onPostExecute方法。我附上了我的密码。 以下是我的主要活动代码:
public void onClick(View v) {
String uri = "";
if(!event.hasImage1())
{
uri = Configuration.SERVER_IP + "/" +event.getImgLink1();
ImageDownloadTask task = new ImageDownloadTask(imageView1, StaffViewEventActivity.this);
task.execute(uri);
}
}
});
然后这是我的Asyntask类的代码:
public class ImageDownloadTask extends AsyncTask<String, Integer, Bitmap> {
private static String TAG = "ImageDownloadTask";
private ImageView imageView;
private StaffViewEventActivity activity;
@Override
protected Bitmap doInBackground(String... params) {
Log.i(TAG, "doInBackground:" + params[0]);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
long length = httpEntity.getContentLength();
Log.i(TAG, "start downloading image");
is = httpEntity.getContent();
if (is != null) {
baos = new ByteArrayOutputStream();
byte[] buf = new byte[128];
int read = -1;
int count = 0;
while ((read = is.read(buf)) != -1) {
baos.write(buf, 0, read);
count += read;
publishProgress((int)(count * 1.0f / length));
}
byte[] data = baos.toByteArray();
Bitmap bit = BitmapFactory.decodeByteArray(data, 0,
data.length);
Log.i(TAG, "finish downloading image");
return bit;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public ImageDownloadTask(ImageView imageView, StaffViewEventActivity activity)
{
this.imageView = imageView;
this.activity =activity;
}
@Override
protected void onProgressUpdate(Integer... progress) {
Log.i("DownloadImgTask", "progress:" + progress[0]);
//photoView.setProgress(progress[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
Log.i(TAG, "onPostExecute");
super.onPostExecute(result);
imageView.setImageBitmap(result);
activity.updateImageStatus(imageView.getId());
}
@Override
protected void onCancelled() {
Log.i(TAG, "DownloadImgTask cancel...");
super.onCancelled();
}
}
doInBackground方法正在运行,我可以通过 task.execute(URI)获得(); 但我无法调用我的onProgressUpdate和onPostExecute。任何人都可以帮我解决这个问题,真的很感激。