Android图片异步加载一之传统的handler+runnable模式

Handler与UI线程是运行在同一线程中的,因为在handler的post(Runnable runnable)方法中,是将Runnable对象放入主线程的消息队列中的(封装成消息对象),该消息队列由Looper管理,然后当handler处理该消息时,会调用Runnable对象的run方法,故使用此方式不能完成图片的异步加载,主界面会等待全部图片加载完成再显示,故此方式会阻塞UI线程

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="图片开始位置"
    />
    <ImageView 
    	android:id="@+id/img1"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    />
    <ImageView 
    	android:id="@+id/img2"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    />
    <ImageView 
    	android:id="@+id/img3"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    />
    <TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="图片结束位置"
    />
</LinearLayout>

 Activity代码:

public class SyncLoadImgTestActivity extends Activity {
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        handler.post(new DownloadThread("http://www.baidu.com/img/baidu_logo.gif",R.id.img1));
        handler.post(new DownloadThread("http://img3.cache.netease.com/www/logo/logo_png.png",R.id.img2));
        handler.post(new DownloadThread("http://www.iteye.com/images/logo.gif?1308833136",R.id.img3));
    }
    
    private Handler handler = new Handler();
    
    class DownloadThread implements Runnable {

    	private String urlStr;
    	private int id;
    	
    	public DownloadThread() {
    		
    	}
    	
    	public DownloadThread(String urlStr,int id) {
    		this.urlStr = urlStr;
    		this.id = id;
    	}
    	
		@Override
		public void run() {
			downloadImg(urlStr,id);
		}
		
		private void downloadImg(String urlStr, int id) { 
			try {
				URL url = new URL(urlStr);
				InputStream is = url.openStream();
				Drawable drawable = Drawable.createFromStream(is, "img");
				ImageView imgview = (ImageView) SyncLoadImgTestActivity.this.findViewById(id);
				imgview.setImageDrawable(drawable);
				Thread.currentThread().sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值