在android异步加载ListView中的图片中使用异步方式加载的图片,当时要的急,写的很粗糙,是为每个图片加载一个线程来实现的。
可以用java concurrent很简明的实现类似功能,并且用到线程池。
这里加载的图片,都是从网上直接获取的。如果用android的UI线程,则需要图片全部加载后才能显示界面。
这里使用了concurrent api通过后台线程并发获取,本例中线程池中只有一个线程,可以设置为多个以加快加载速度。可参见使用java concurrent处理并发需求中的简单示例了解concurrent api的基本机制。
代码不复杂:
package com.easymorse.lazyload; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.widget.ImageView; public class LazyLoadImageActivity extends Activity { private ExecutorService executorService = Executors.newFixedThreadPool(1); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); loadImage("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1); loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.image2); loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3); } @Override protected void onDestroy() { executorService.shutdown(); super.onDestroy(); } private void loadImage(final String url, final int id) { final Handler handler=new Handler(); executorService.submit(new Runnable() { @Override public void run() { try { final Drawable drawable = Drawable.createFromStream( new URL(url).openStream(), "image.png"); handler.post(new Runnable() { @Override public void run() { ((ImageView) LazyLoadImageActivity.this .findViewById(id)) .setImageDrawable(drawable); } }); } catch (Exception e) { throw new RuntimeException(e); } } }); } }
完整源代码见:
http://easymorse.googlecode.com/svn/tags/lazy.load.image-0.2.0/
可以对比一下不做异步处理的示例:
http://easymorse.googlecode.com/svn/tags/lazy.load.image-0.1.0/