使用Handler更新图片,结合了HttpCliet 和ProgressDialog

首先是java文件代码

public class MainActivity extends Activity {

	private String image_path = "https://www.baidu.com/img/bdlogo.png";
	private Button button;
	private ImageView imageView;
	private ProgressDialog dialog;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			byte[] bit = (byte[]) msg.obj;
			Bitmap bitmap = BitmapFactory.decodeByteArray(bit, 0, bit.length); // 把数据设置为bitmpa
			imageView.setImageBitmap(bitmap);
			if (msg.what == 1) {
				dialog.dismiss();// 隐藏progressDialog
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		button = (Button) findViewById(R.id.button1);
		imageView = (ImageView) findViewById(R.id.image);
		dialog = new ProgressDialog(this);
		dialog.setTitle("下载任务");
		dialog.setMessage("loading......");
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new Thread(new MyRunnable()).start();// 开启线程去执行下载任务
				dialog.show();// 显示progresDialog
			}
		});
	}

	class MyRunnable implements Runnable {

		@Override
		public void run() {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(image_path);
			try {
				HttpResponse response = client.execute(get);
				if (response.getStatusLine().getStatusCode() == 200) {
					byte[] resule = EntityUtils.toByteArray(response
							.getEntity());
					Message message = Message.obtain();
					message.obj = resule;
					message.what = 1;
					handler.sendMessage(message);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				client.getConnectionManager().shutdown();// 最后要关闭
			}
		}

	}
}

然后是xml中的布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="78dp"
        android:text="下载图片" />

</RelativeLayout>


最后记得要在注册文件中,写上Intenet的权限,效果如下



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值