在android中更新UI爲非線程安全的。所以想在線程中更新UI必須和Handler配合。 java
例: android
private ImageView imgHead; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: imgHead.setImageBitmap((Bitmap)msg.obj); break; default: break; } } }; Runnable downloadRun = new Runnable(){ @Override public void run() { URL url; Bitmap bitmap = null; try { url = new URL("http://tp1.sinaimg.cn/2118986604/180/5633348097/1"); InputStream is = url.openConnection().getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bitmap = BitmapFactory.decodeStream(bis); bis.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } handler.obtainMessage(1,bitmap).sendToTarget(); //Bitmap bitmap = getBitmapFromUrl("http://tp1.sinaimg.cn/2118986604/50/5633348097/1"); //imgHead.setImageBitmap(bitmap); //imgHead.invalidate(); } }; protected void onCreate(Bundle savedInstanceState) { imgHead=(ImageView) this.findViewById(R.id.img_head); new Thread(downloadRun).start(); }