android異步更新UI

 android下面圖片更新是需要啓動多個子線程來進行的,而android下面是並不是線程安全的,所以thread這裏是用不了的,只能用runnable接口。

廢話不多說了 直接上代碼。

1、下載線程  繼承runnable接口

public class DownloadImage implements Runnable {

 

private ImageView p_w_picpathView;

private String p_w_picpathUrl;

private Bitmap bitmap;

 

        //構造的時候傳入要更新的ImageView ,同時傳入圖片的URL

public DownloadImage(ImageView p_w_picpathView, String p_w_picpathUrl) {

super();

this.p_w_picpathView = p_w_picpathView;

this.p_w_picpathUrl = p_w_picpathUrl;

}

public Handler handler = new Handler();

Runnable updateResults = new Runnable() {

 

@Override

public void run() {

updateUI();

}

};

public void run() {

HttpGet httpRequest = null;

URL url;

try {

url = new URL(p_w_picpathUrl);

httpRequest = new HttpGet(url.toURI());

HttpClient httpclient = new DefaultHttpClient();

HttpResponse response = (HttpResponse) httpclient

        .execute(httpRequest);

HttpEntity entity = response.getEntity();

BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);

InputStream instream = bufHttpEntity.getContent();

   bitmap = BitmapFactory.decodeStream(instream);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

handler.post(updateResults);

}

public void updateUI(){

p_w_picpathView.setImageBitmap(bitmap);

}

}

2、主程序

ImageView p_w_picpathView = (ImageView)findViewById(R.id.p_w_picpath);

String p_w_picpathUrl = "http://www.qqzhi.com/show/UploadPic/2010-5/2010521102357899.jpg";

 new Thread(new DownloadImage(p_w_picpathView, p_w_picpathUrl)).start();

這些添加在oncreate()裏面就實現了圖片的更新了  

 

3、配置文件AndroidManifest

<uses-permission android:name="android.permission.INTERNET"/>
獲取訪問網絡權限

 

4、佈局文件

<ImageView

android:id="@+id/p_w_picpath"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_x = "100px"

android:layout_y = "100px"

android:src="@drawable/icon"

/>

 

 

OK,要實現的功能就完全實現了,你可以定義N個變量(就是你需要更新的圖片),目前我測試一次更新20幅消耗時間1s。

希望能對大家有所幫助,有興趣可以一起討論!

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章