1. Activity代码
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;public class HandlerActivity extends Activity {private Button button = null;private ImageView imageView = null;private String image_path = "http://11.203.18.14:8080/image/001.png";private ProgressDialog dialog = null;private static final int IS_FINISH = 1;private Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubbyte[] data = (byte[])msg.obj;Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);imageView.setImageBitmap(bm);if(msg.what == IS_FINISH){dialog.dismiss();}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);button = (Button)findViewById(R.id.button1);imageView = (ImageView)findViewById(R.id.imageView1);dialog = new ProgressDialog(HandlerActivity.this);dialog.setTitle("提示");dialog.setMessage("正在下载,请稍后......");dialog.setCancelable(false);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubnew Thread(new MyThread()).start();}});}//重新定义一个线程public class MyThread implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubHttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(image_path);HttpResponse httpResponse = null;
// InputStream inputStream = null;try{httpResponse = httpClient.execute(httpGet);if(httpResponse.getStatusLine().getStatusCode()==200){byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());Message message = Message.obtain();message.obj = data;message.what = IS_FINISH;handler.sendMessage(message);}}catch(Exception e){e.printStackTrace();}}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.handler, menu);return true;}}
2. main.xml文件
3. 注册文件添加网络连接