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

Android中加載網(wǎng)絡(luò)資源時(shí)的優(yōu)化可使用(線程+緩存)解決

 更新時(shí)間:2013年06月03日 16:11:45   作者:  
Android 中加載網(wǎng)絡(luò)資源時(shí)的優(yōu)化;基本的思路是線程+緩存來解決,具體解決思路如下,有類似情況的朋友可以參考下哈
網(wǎng)上關(guān)于這個(gè)方面的文章也不少,基本的思路是線程+緩存來解決。下面提出一些優(yōu)化:
1、采用線程池
2、內(nèi)存緩存+文件緩存
3、內(nèi)存緩存中網(wǎng)上很多是采用SoftReference來防止堆溢出,這兒嚴(yán)格限制只能使用最大JVM內(nèi)存的1/4
4、對(duì)下載的圖片進(jìn)行按比例縮放,以減少內(nèi)存的消耗

具體的代碼里面說明。先放上內(nèi)存緩存類的代碼MemoryCache.java:
復(fù)制代碼 代碼如下:

<SPAN style="FONT-SIZE: 18px"><STRONG>public class MemoryCache {
private static final String TAG = "MemoryCache";
// 放入緩存時(shí)是個(gè)同步操作
// LinkedHashMap構(gòu)造方法的最后一個(gè)參數(shù)true代表這個(gè)map里的元素將按照最近使用次數(shù)由少到多排列,即LRU
// 這樣的好處是如果要將緩存中的元素替換,則先遍歷出最近最少使用的元素來替換以提高效率
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
// 緩存中圖片所占用的字節(jié),初始0,將通過此變量嚴(yán)格控制緩存所占用的堆內(nèi)存
private long size = 0;// current allocated size
// 緩存只能占用的最大堆內(nèi)存
private long limit = 1000000;// max memory in bytes
public MemoryCache() {
// use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
/**
* 嚴(yán)格控制堆內(nèi)存,如果超過將首先替換最近最少使用的那個(gè)圖片緩存
*
*/
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
// 先遍歷最近最少使用的元素
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
cache.clear();
}
/**
* 圖片占用的內(nèi)存
*
* @param bitmap
* @return
*/
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}</STRONG></SPAN>

也可以使用SoftReference,代碼會(huì)簡單很多,但是我推薦上面的方法。
復(fù)制代碼 代碼如下:

public class MemoryCache {

private Map<String, SoftReference<Bitmap>> cache = Collections
.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
public Bitmap get(String id) {
if (!cache.containsKey(id))
return null;
SoftReference<Bitmap> ref = cache.get(id);
return ref.get();
}
public void put(String id, Bitmap bitmap) {
cache.put(id, new SoftReference<Bitmap>(bitmap));
}
public void clear() {
cache.clear();
}
}

下面是文件緩存類的代碼FileCache.java:
復(fù)制代碼 代碼如下:

public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// 如果有SD卡則在SD卡中建一個(gè)LazyList的目錄存放緩存的圖片
// 沒有SD卡就放在系統(tǒng)的緩存目錄中
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"LazyList");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
// 將url的hashCode作為緩存的文件名
String filename = String.valueOf(url.hashCode());
// Another possible solution
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}

最后最重要的加載圖片的類,ImageLoader.java:
復(fù)制代碼 代碼如下:

public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
// 線程池
ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
// 當(dāng)進(jìn)入listview時(shí)默認(rèn)的圖片,可換成你自己的默認(rèn)圖片
final int stub_id = R.drawable.stub;
// 最主要的方法
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
// 先從內(nèi)存緩存中查找
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
// 若沒有的話則開啟新線程加載圖片
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// 先從文件緩存中查找是否有
Bitmap b = decodeFile(f);
if (b != null)
return b;
// 最后從指定的url中下載圖片
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// decode這個(gè)圖片并且按比例縮放以減少內(nèi)存消耗,虛擬機(jī)對(duì)每張圖片的緩存大小也是有限制的
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
// 更新的操作放在UI線程中
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
/**
* 防止圖片錯(cuò)位
*
* @param photoToLoad
* @return
*/
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// 用于在UI線程中更新界面
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
}

主要流程是先從內(nèi)存緩存中查找,若沒有再開線程,從文件緩存中查找都沒有則從指定的url中查找,并對(duì)bitmap進(jìn)行處理,最后通過下面方法對(duì)UI進(jìn)行更新操作。
復(fù)制代碼 代碼如下:

a.runOnUiThread(...);

在你的程序中的基本用法:
復(fù)制代碼 代碼如下:

<SPAN style="FONT-SIZE: 18px"><STRONG>ImageLoader imageLoader=new ImageLoader(context);
...
imageLoader.DisplayImage(url, imageView);</STRONG></SPAN>

比如你的放在你的ListView的adapter的getView()方法中,當(dāng)然也適用于GridView。

相關(guān)文章

  • Flutter應(yīng)用框架搭建之屏幕適配詳解

    Flutter應(yīng)用框架搭建之屏幕適配詳解

    因移動(dòng)設(shè)備的多樣性,特別是 Android 的碎片化嚴(yán)重,存在各種各樣的分辨率,而 Flutter 跨平臺(tái)開發(fā)又需同時(shí)支持 Android 和 iOS ,為盡可能的還原設(shè)計(jì)圖效果提升用戶體驗(yàn),屏幕適配就勢在必行了。本文將詳細(xì)講解Flutter屏幕適配的方法,需要的可以參考一下
    2022-03-03
  • Android item長按刪除功能

    Android item長按刪除功能

    這篇文章主要介紹了Android item長按刪除功能,在文章底部給大家介紹了android 長按刪除listview的item的實(shí)例代碼,需要的的朋友參考下
    2017-07-07
  • Kotlin中的密封類和密封接口及其應(yīng)用場景

    Kotlin中的密封類和密封接口及其應(yīng)用場景

    在Kotlin中,密封類和密封接口是用于表示受限類型層次結(jié)構(gòu)的特殊類和接口。密封類和密封接口可以在一定程度上限制類型的繼承層次,使編譯器能夠更好地檢測代碼中的錯(cuò)誤,并增強(qiáng)代碼的可讀性和可維護(hù)性
    2023-05-05
  • 更新至Android Studio4.1后發(fā)現(xiàn)as打不開的解決方法(原因分析)

    更新至Android Studio4.1后發(fā)現(xiàn)as打不開的解決方法(原因分析)

    這篇文章主要介紹了更新至Android Studio4.1后發(fā)現(xiàn)as打不開的解決方案,本文給大家分享問題所在原因給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-10-10
  • Android創(chuàng)建淡入淡出動(dòng)畫的詳解

    Android創(chuàng)建淡入淡出動(dòng)畫的詳解

    大家好,本篇文章主要講的是Android創(chuàng)建淡入淡出動(dòng)畫的詳解,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • android實(shí)現(xiàn)倒計(jì)時(shí)動(dòng)態(tài)圈

    android實(shí)現(xiàn)倒計(jì)時(shí)動(dòng)態(tài)圈

    這篇文章主要為大家詳細(xì)介紹了android實(shí)現(xiàn)倒計(jì)時(shí)動(dòng)態(tài)圈,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-01-01
  • OkHttp原理分析小結(jié)

    OkHttp原理分析小結(jié)

    OkHttp 是 Square 公司開源的一款網(wǎng)絡(luò)框架,封裝了一個(gè)高性能的 http 請(qǐng)求庫,本文對(duì)OkHttp原理給大家詳細(xì)講解,感興趣的朋友跟隨小編一起看看吧
    2024-01-01
  • Android開發(fā)之基本控件和四種布局方式詳解

    Android開發(fā)之基本控件和四種布局方式詳解

    這篇文章主要介紹了Android開發(fā)之基本控件和四種布局方式詳解的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-06-06
  • 淺談Android為RecyclerView增加監(jiān)聽以及數(shù)據(jù)混亂的小坑

    淺談Android為RecyclerView增加監(jiān)聽以及數(shù)據(jù)混亂的小坑

    下面小編就為大家?guī)硪黄獪\談Android為RecyclerView增加監(jiān)聽以及數(shù)據(jù)混亂的小坑。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-04-04
  • Android getActivity()為空的問題解決辦法

    Android getActivity()為空的問題解決辦法

    這篇文章主要介紹了Android getActivity()為空的問題解決辦法的相關(guān)資料,導(dǎo)致apk空指針崩潰問題,很嚴(yán)重的問題,為了解決這問題,上網(wǎng)搜索了很多資料,需要的朋友可以參考下
    2017-07-07

最新評(píng)論