欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 異步加載圖片分析總結(jié)

 更新時(shí)間:2013年06月03日 16:18:29   作者:  
研究了android從網(wǎng)絡(luò)上異步加載圖像,現(xiàn)總結(jié)如下,感興趣的朋友可以了解下哈

研究了android從網(wǎng)絡(luò)上異步加載圖像,現(xiàn)總結(jié)如下:
(1)由于android UI更新支持單一線程原則,所以從網(wǎng)絡(luò)上取數(shù)據(jù)并更新到界面上,為了不阻塞主線程首先可能會(huì)想到以下方法。

在主線程中new 一個(gè)Handler對(duì)象,加載圖像方法如下所示

復(fù)制代碼 代碼如下:

private void loadImage(final String url, final int id) {
handler.post(new Runnable() {
public void run() {
Drawable drawable = null;
try {
drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
} catch (IOException e) {
}
((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
}
});
}

上面這個(gè)方法缺點(diǎn)很顯然,經(jīng)測(cè)試,如果要加載多個(gè)圖片,這并不能實(shí)現(xiàn)異步加載,而是等到所有的圖片都加載完才一起顯示,因?yàn)樗鼈兌歼\(yùn)行在一個(gè)線程中。

然后,我們可以簡(jiǎn)單改進(jìn)下,將Handler+Runnable模式改為Handler+Thread+Message模式不就能實(shí)現(xiàn)同時(shí)開啟多個(gè)線程嗎?
(2)在主線程中new 一個(gè)Handler對(duì)象,代碼如下:
復(fù)制代碼 代碼如下:

final Handler handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
}
};

對(duì)應(yīng)加載圖像代碼如下:
復(fù)制代碼 代碼如下:

//采用handler+Thread模式實(shí)現(xiàn)多線程異步加載
private void loadImage2(final String url, final int id) {
Thread thread = new Thread(){
@Override
public void run() {
Drawable drawable = null;
try {
drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
} catch (IOException e) {
}
 
Message message= handler2.obtainMessage() ;
message.arg1 = id;
message.obj = drawable;
handler2.sendMessage(message);
}
};
thread.start();
thread = null;
}

這樣就簡(jiǎn)單實(shí)現(xiàn)了異步加載了。細(xì)想一下,還可以優(yōu)化的,比如引入線程池、引入緩存等,我們先介紹線程池。
(3)引入ExecutorService接口,于是代碼可以優(yōu)化如下:
在主線程中加入:private ExecutorService executorService = Executors.newFixedThreadPool(5);
對(duì)應(yīng)加載圖像方法更改如下:
復(fù)制代碼 代碼如下:

// 引入線程池來管理多線程
private void loadImage3(final String url, final int id) {
executorService.submit(new Runnable() {
public void run() {
try {
final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
handler.post(new Runnable() {
 
public void run() {
((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}

4)為了更方便使用我們可以將異步加載圖像方法封裝一個(gè)類,對(duì)外界只暴露一個(gè)方法即可,考慮到效率問題我們可以引入內(nèi)存緩存機(jī)制,做法是建立一個(gè)HashMap,其鍵(key)為加載圖像url,其值(value)是圖像對(duì)象Drawable。先看一下我們封裝的類
復(fù)制代碼 代碼如下:

public class AsyncImageLoader3 {
//為了加快速度,在內(nèi)存中開啟緩存(主要應(yīng)用于重復(fù)圖片較多時(shí),或者同一個(gè)圖片要多次被訪問,比如在ListView時(shí)來回滾動(dòng))
public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
private ExecutorService executorService = Executors.newFixedThreadPool(5); //固定五個(gè)線程來執(zhí)行任務(wù)
private final Handler handler=new Handler();
&nbsp;
/**
*
* @param imageUrl 圖像url地址
* @param callback 回調(diào)接口
* <a href="\"http://www.eoeandroid.com/home.php?mod=space&uid=7300\"" target="\"_blank\"">@return</a> 返回內(nèi)存中緩存的圖像,第一次加載返回null
*/
public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
//如果緩存過就從緩存中取出數(shù)據(jù)
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
if (softReference.get() != null) {
return softReference.get();
}
}
//緩存中沒有圖像,則從網(wǎng)絡(luò)上取出數(shù)據(jù),并將取出的數(shù)據(jù)緩存到內(nèi)存中
executorService.submit(new Runnable() {
public void run() {
try {
final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
&nbsp;
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
&nbsp;
handler.post(new Runnable() {
public void run() {
callback.imageLoaded(drawable);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
return null;
}
//從網(wǎng)絡(luò)上取數(shù)據(jù)方法
protected Drawable loadImageFromUrl(String imageUrl) {
try {
return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//對(duì)外界開放的回調(diào)接口
public interface ImageCallback {
//注意 此方法是用來設(shè)置目標(biāo)對(duì)象的圖像資源
public void imageLoaded(Drawable imageDrawable);
}
}

這樣封裝好后使用起來就方便多了。在主線程中首先要引入AsyncImageLoader3 對(duì)象,然后直接調(diào)用其loadDrawable方法即可,需要注意的是ImageCallback接口的imageLoaded方法是唯一可以把加載的圖 像設(shè)置到目標(biāo)ImageView或其相關(guān)的組件上。

在主線程調(diào)用代碼:
先實(shí)例化對(duì)象 private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
調(diào)用異步加載方法:
復(fù)制代碼 代碼如下:

//引入線程池,并引入內(nèi)存緩存功能,并對(duì)外部調(diào)用封裝了接口,簡(jiǎn)化調(diào)用過程
private void loadImage4(final String url, final int id) {
//如果緩存過就會(huì)從緩存中取出圖像,ImageCallback接口中方法也不會(huì)被執(zhí)行
Drawable cacheImage = asyncImageLoader.loadDrawable(url,new AsyncImageLoader.ImageCallback() {
//請(qǐng)參見實(shí)現(xiàn):如果第一次加載url時(shí)下面方法會(huì)執(zhí)行
public void imageLoaded(Drawable imageDrawable) {
((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
}
});
if(cacheImage!=null){
((ImageView) findViewById(id)).setImageDrawable(cacheImage);
}
}

5)同理,下面也給出采用Thread+Handler+MessageQueue+內(nèi)存緩存代碼,原則同(4),只是把線程池?fù)Q成了Thread+Handler+MessageQueue模式而已。代碼如下:
復(fù)制代碼 代碼如下:

public class AsyncImageLoader {
//為了加快速度,加入了緩存(主要應(yīng)用于重復(fù)圖片較多時(shí),或者同一個(gè)圖片要多次被訪問,比如在ListView時(shí)來回滾動(dòng))
private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
&nbsp;
/**
*
* @param imageUrl 圖像url地址
* @param callback 回調(diào)接口
* @return 返回內(nèi)存中緩存的圖像,第一次加載返回null
*/
public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
//如果緩存過就從緩存中取出數(shù)據(jù)
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
if (softReference.get() != null) {
return softReference.get();
}
}
&nbsp;
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
callback.imageLoaded((Drawable) msg.obj);
}
};
new Thread() {
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
handler.sendMessage(handler.obtainMessage(0, drawable));
&nbsp;
}
&nbsp;
}.start();
/*
下面注釋的這段代碼是Handler的一種代替方法
*/
// new AsyncTask() {
// @Override
// protected Drawable doInBackground(Object... objects) {
// Drawable drawable = loadImageFromUrl(imageUrl);
// imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
// return drawable;
// }
//
// @Override
// protected void onPostExecute(Object o) {
// callback.imageLoaded((Drawable) o);
// }
// }.execute();
return null;
}
&nbsp;
protected Drawable loadImageFromUrl(String imageUrl) {
try {
return Drawable.createFromStream(new URL(imageUrl).openStream(), "src");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//對(duì)外界開放的回調(diào)接口
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable);
}
}

至此,異步加載就介紹完了,下面給出的代碼為測(cè)試用的完整代碼:
復(fù)制代碼 代碼如下:

package com.bshark.supertelphone.activity;
&nbsp;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import com.bshark.supertelphone.R;
import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader;
import com.bshark.supertelphone.ui.adapter.util.AsyncImageLoader3;
&nbsp;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
&nbsp;
public class LazyLoadImageActivity extends Activity {
final Handler handler=new Handler();
final Handler handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
}
};
private ExecutorService executorService = Executors.newFixedThreadPool(5); //固定五個(gè)線程來執(zhí)行任務(wù)
private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
&nbsp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
&nbsp;
// 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);
// loadImage("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
// loadImage("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
&nbsp;
loadImage2("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
loadImage2("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
loadImage2("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
loadImage2("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
loadImage2("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
// loadImage3("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
// loadImage3("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
// loadImage3("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
// loadImage3("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
// loadImage3("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
&nbsp;
// loadImage4("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
// loadImage4("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
// loadImage4("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
// loadImage4("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
// loadImage4("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
&nbsp;
// loadImage5("http://www.chinatelecom.com.cn/images/logo_new.gif", R.id.image1);
// //為了測(cè)試緩存而模擬的網(wǎng)絡(luò)延時(shí)
// SystemClock.sleep(2000);
// loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image2);
// SystemClock.sleep(2000);
// loadImage5("http://cache.soso.com/30d/img/web/logo.gif", R.id.image3);
// SystemClock.sleep(2000);
// loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
// SystemClock.sleep(2000);
// loadImage5("http://cache.soso.com/30d/img/web/logo.gif", R.id.image5);
// SystemClock.sleep(2000);
// loadImage5("http://www.baidu.com/img/baidu_logo.gif", R.id.image4);
}
&nbsp;
@Override
protected void onDestroy() {
executorService.shutdown();
super.onDestroy();
}
//線程加載圖像基本原理
private void loadImage(final String url, final int id) {
handler.post(new Runnable() {
public void run() {
Drawable drawable = null;
try {
drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
} catch (IOException e) {
}
((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
}
});
}
//采用handler+Thread模式實(shí)現(xiàn)多線程異步加載
private void loadImage2(final String url, final int id) {
Thread thread = new Thread(){
@Override
public void run() {
Drawable drawable = null;
try {
drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
} catch (IOException e) {
}
&nbsp;
Message message= handler2.obtainMessage() ;
message.arg1 = id;
message.obj = drawable;
handler2.sendMessage(message);
}
};
thread.start();
thread = null;
}
// 引入線程池來管理多線程
private void loadImage3(final String url, final int id) {
executorService.submit(new Runnable() {
public void run() {
try {
final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
handler.post(new Runnable() {
&nbsp;
public void run() {
((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
//引入線程池,并引入內(nèi)存緩存功能,并對(duì)外部調(diào)用封裝了接口,簡(jiǎn)化調(diào)用過程
private void loadImage4(final String url, final int id) {
//如果緩存過就會(huì)從緩存中取出圖像,ImageCallback接口中方法也不會(huì)被執(zhí)行
Drawable cacheImage = asyncImageLoader.loadDrawable(url,new AsyncImageLoader.ImageCallback() {
//請(qǐng)參見實(shí)現(xiàn):如果第一次加載url時(shí)下面方法會(huì)執(zhí)行
public void imageLoaded(Drawable imageDrawable) {
((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
}
});
if(cacheImage!=null){
((ImageView) findViewById(id)).setImageDrawable(cacheImage);
}
}
&nbsp;
//采用Handler+Thread+封裝外部接口
private void loadImage5(final String url, final int id) {
//如果緩存過就會(huì)從緩存中取出圖像,ImageCallback接口中方法也不會(huì)被執(zhí)行
Drawable cacheImage = asyncImageLoader3.loadDrawable(url,new AsyncImageLoader3.ImageCallback() {
//請(qǐng)參見實(shí)現(xiàn):如果第一次加載url時(shí)下面方法會(huì)執(zhí)行
public void imageLoaded(Drawable imageDrawable) {
((ImageView) findViewById(id)).setImageDrawable(imageDrawable);
}
});
if(cacheImage!=null){
((ImageView) findViewById(id)).setImageDrawable(cacheImage);
}
}
&nbsp;
&nbsp;
}

xml文件大致如下:
復(fù)制代碼 代碼如下:

<SPAN style="FONT-SIZE: 18px"><STRONG>< ?xml version="1.0" encoding="utf-8"?>
&nbsp;
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent" >
<ImageView android:id="@+id/image1" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image2" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image3" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image5" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
<ImageView android:id="@+id/image4" android:layout_height="wrap_content" android:layout_width="fill_parent"></ImageView>
< /LinearLayout></STRONG></SPAN>

相關(guān)文章

  • Android自定義AvatarImageView實(shí)現(xiàn)頭像顯示效果

    Android自定義AvatarImageView實(shí)現(xiàn)頭像顯示效果

    這篇文章主要為大家詳細(xì)介紹了Android自定義AvatarImageView實(shí)現(xiàn)頭像顯示效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • Android開發(fā)中MotionEvent坐標(biāo)獲取方法分析

    Android開發(fā)中MotionEvent坐標(biāo)獲取方法分析

    這篇文章主要介紹了Android開發(fā)中MotionEvent坐標(biāo)獲取方法,結(jié)合實(shí)例形式分析了MotionEvent獲取坐標(biāo)的相關(guān)函數(shù)使用方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2016-02-02
  • Android仿探探卡片式滑動(dòng)效果實(shí)現(xiàn)

    Android仿探探卡片式滑動(dòng)效果實(shí)現(xiàn)

    之前在玩探探看著效果圖還可以,然后又在網(wǎng)上看到了一相關(guān)的介紹,便想著自己動(dòng)手來實(shí)踐下,所以下面這篇文章主要介紹了關(guān)于Android實(shí)現(xiàn)仿探探卡片式左右滑動(dòng)效果的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-03-03
  • Android 自定義標(biāo)題欄背景

    Android 自定義標(biāo)題欄背景

    最近在做android項(xiàng)目,需要做一個(gè)自定義的標(biāo)題欄(操作欄)。去網(wǎng)上找了很多demo,發(fā)現(xiàn)都有很多問題。例如使用自定義的style。下面來分享下個(gè)人最終的解決方案吧
    2016-01-01
  • Android開發(fā) Activity和Fragment詳解

    Android開發(fā) Activity和Fragment詳解

    本文主要介紹Android開發(fā) Activity和Fragment,這里對(duì)Activity和Fragment的知識(shí)做了詳細(xì)講解,并附簡(jiǎn)單代碼示例,有興趣的小伙伴可以參考下
    2016-08-08
  • Android獲取本機(jī)電話號(hào)碼的簡(jiǎn)單方法

    Android獲取本機(jī)電話號(hào)碼的簡(jiǎn)單方法

    Android獲取本機(jī)電話號(hào)碼的簡(jiǎn)單方法,需要的朋友可以參考一下
    2013-05-05
  • Android?ASM插樁探索實(shí)戰(zhàn)詳情

    Android?ASM插樁探索實(shí)戰(zhàn)詳情

    這篇文章主要介紹了Android?ASM插樁探索實(shí)戰(zhàn)詳情,文章圍繞主題展開詳細(xì)的內(nèi)容戒殺,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • 淺談Android中使用異步線程更新UI視圖的幾種方法

    淺談Android中使用異步線程更新UI視圖的幾種方法

    本篇文章主要介紹了淺談Android中使用異步線程更新UI視圖的幾種方法,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-08-08
  • 詳解Flutter中視頻播放器插件的使用教程

    詳解Flutter中視頻播放器插件的使用教程

    視頻播放器插件是可用于Flutter的常用插件之一,在這篇文章中,將學(xué)習(xí)如何應(yīng)用視頻播放器插件以及控制視頻播放器的不同功能,感興趣的可以了解一下
    2022-02-02
  • 完美解決Android App啟動(dòng)頁(yè)有白屏閃過的問題

    完美解決Android App啟動(dòng)頁(yè)有白屏閃過的問題

    這篇文章主要介紹了完美解決Android App啟動(dòng)頁(yè)有白屏閃過的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08

最新評(píng)論