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(); } } }}
?