安卓多线程编程系列3:使用handler和message下载网络图片

使用handler和message进行网络操作是多线程编程经常使用的形式,下面我们来一起看一下它的使用方法。

整体思路:触发一个事件,在这个事件中开启一个线程,在这个线程中定义消息,在消息中携带数据,通过handler发送过去,在handler中的handleMessage中去处理消息,获取数据。具体而言,在xml文件中放置一个Button控件和一个ImageView控件,在activity中,定义一个MyThread类,继承Runnable这个类,重写里面的run方法,在这个方法中获取网络图片,并将网络图片对象赋值给message的obj,把定义的常量IS_FINISH赋值给message的what,发送message,定义一个Handler对象,在这个对象中重写handleMessage这个方法,在这个方法中获取到message中传递的信息,并将图片对象绑定到ImageView控件上,根据判断的what的值,来执行对话框的消失操作。注意在清单文件AndroidManifest.xml中添加网络授权。

activity_main.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>
MainActivity.java文件:

package com.example.android_handler_message;
//使用handler和message下载图片并展示
import java.io.InputStream;

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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
//不能在UI主线程中直接访问网络
	private Button button;
	private ImageView imageView;
	private String image_path="http://pica.nipic.com/2007-11-09/200711912453162_2.jpg";
	private final int IS_FINISH=1;
	private ProgressDialog dialog=null;
	private Handler handler=new Handler(){
		@Override
		public void handleMessage(android.os.Message msg) {
//			数据的接收
			byte[] data=(byte[])msg.obj;
//			对字节数组进行解码
			Bitmap bm=BitmapFactory.decodeByteArray(data, 0, data.length);
			imageView.setImageBitmap(bm);
			if(msg.what==IS_FINISH){
				dialog.dismiss();
			}
		};
	};
	@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.imageView1);
//		定义一个滚动条对话框
		dialog=new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("正在下载,请稍后...");
		dialog.setCancelable(false);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
                 new Thread(new MyThread()).start();
                 dialog.show();
			}
		});
	}
	
	public class MyThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			HttpClient 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){
//					返回一个输入流
//					inputStream=httpResponse.getEntity().getContent();
					byte[] data=EntityUtils.toByteArray(httpResponse.getEntity());
//					使用message携带数据
//					为什么不采用这种方式Message message=new Message();定义消息呢?
//					使用Message message=Message.obtain();可以减少内存空间,sPool这个对象为空的时候才构建对象
//					如果sPool这个对象不为空的话,可以从消息池中取出重复使用。
					Message message=Message.obtain();
					message.obj=data;
					message.what=IS_FINISH;
//					handler发送message
					handler.sendMessage(message);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		
	} 

	@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;
	}

}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值