在android中使用AsyncTask从网络中下载图片,但是调用了execute方法后,最后不执行onPostExcute方法,以下为源码,请哪位高手帮忙给看看,多谢!
package com.example.testasynctask;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Button btnButton = null;
private ImageView imageView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
btnButton = (Button)findViewById(R.id.button1);
btnButton.setOnClickListener(new ButtonClick());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private final class ButtonClick implements OnClickListener
{
@Override
public void onClick(View arg0) {
DownImage downImage = new DownImage(MainActivity.this);
downImage.execute(“http://www.baidu.com/img/bdlogo.png”);
}
}
private class DownImage extends AsyncTask<String, Void, Bitmap>
{
private ProgressDialog progressDialog =null;
public DownImage(Context context)
{
progressDialog = ProgressDialog.show(context, “”, “正在下载”);
}
protected void onPreExcute()
{
}
@Override
protected Bitmap doInBackground(String… urls) {
URL url =null;
try {
url = new URL(urls[0]);
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
conn.setConnectTimeout(5000);
try {
conn.setRequestMethod(“GET”);
} catch (ProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ByteArrayOutputStream outputStream =null;
try {
if(conn.getResponseCode() == 200)
{
InputStream inputStream = conn.getInputStream();
byte []buffer = new byte[1024];
outputStream = new ByteArrayOutputStream();
int len= 0;
while((len = inputStream.read(buffer)) != -1)
{
outputStream.write(buffer,0,len);
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeByteArray(outputStream.toByteArray(), 0, outputStream.toByteArray().length);
return bmp;
}
protected void onPostExcute(Bitmap bmp) {
imageView.setImageBitmap(bmp);
progressDialog.dismiss();
}
}
}