如何在Android中高效管理圖片加載
首先我們需要在配置AndroidManifest.xml里面添加
<uses-permission android:name="android.permission.INTERNET" />
在Android應(yīng)用中實(shí)現(xiàn)圖片緩存和下載
在現(xiàn)代移動(dòng)應(yīng)用開發(fā)中,用戶體驗(yàn)至關(guān)重要,特別是在圖像加載方面。為了提高應(yīng)用的響應(yīng)速度和減少網(wǎng)絡(luò)流量,我們通常采用緩存機(jī)制來存儲(chǔ)下載的圖片。本文將介紹如何在Android中實(shí)現(xiàn)一個(gè)簡單的圖片緩存加載器,允許從網(wǎng)絡(luò)下載圖片并緩存到本地。
項(xiàng)目結(jié)構(gòu)
我們將構(gòu)建一個(gè)名為 ImageCacheLoader
的類,該類負(fù)責(zé)從URL加載圖片,并首先檢查本地緩存。如果緩存不存在,則從網(wǎng)絡(luò)下載圖片。
使用
package com.example.dowhttppic; import android.os.Bundle; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import android.os.Bundle; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private ImageView imageView; private ImageCacheLoader imageCacheLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); // 初始化 ImageCacheLoader imageCacheLoader = new ImageCacheLoader(this); // 加載圖片 String imageUrl = "圖片鏈接"; imageCacheLoader.loadImage(imageUrl, imageView); } }
代碼解析
package com.example.dowhttppic; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.widget.ImageView; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class ImageCacheLoader { private Context context; private Handler handler = new Handler(); // 用于處理UI線程更新 // 構(gòu)造函數(shù),接收上下文 public ImageCacheLoader(Context context) { this.context = context; } // 公共方法:加載圖片,首先從緩存讀取,如果沒有則通過網(wǎng)絡(luò)下載 public void loadImage(final String url, final ImageView imageView) { // 獲取緩存目錄 File cacheDir = context.getCacheDir(); String fileName = getFileNameFromUrl(url); final File imageFile = new File(cacheDir, fileName); // 如果本地有緩存,直接加載本地圖片 if (imageFile.exists()) { Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath()); imageView.setImageBitmap(bitmap); } else { // 啟動(dòng)線程下載圖片并緩存 new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = downloadImage(url); if (bitmap != null) { saveImageToCache(imageFile, bitmap); // 更新UI,需在主線程中執(zhí)行 handler.post(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } else { // 超時(shí)或下載失敗時(shí)顯示默認(rèn)圖片 handler.post(new Runnable() { @Override public void run() { imageView.setImageResource(R.drawable.no_image_dow_http); } }); } } }).start(); } } // 從網(wǎng)絡(luò)下載圖片,添加超時(shí)機(jī)制 private Bitmap downloadImage(String urlString) { Bitmap bitmap = null; try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); // 設(shè)置連接超時(shí)為5秒 connection.setReadTimeout(5000); // 設(shè)置讀取超時(shí)為5秒 connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } return bitmap; } // 將下載的圖片保存到本地緩存 private void saveImageToCache(File imageFile, Bitmap bitmap) { try { OutputStream outputStream = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } // 根據(jù)URL提取文件名 private String getFileNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); } }
關(guān)鍵功能解析
1. 圖片加載方法
loadImage
方法是該類的核心,它負(fù)責(zé)加載指定URL的圖片。首先,它嘗試從本地緩存讀取圖片,如果緩存存在,則直接使用緩存的圖片;如果不存在,則啟動(dòng)一個(gè)新線程下載圖片。
public void loadImage(final String url, final ImageView imageView) { File cacheDir = context.getCacheDir(); String fileName = getFileNameFromUrl(url); final File imageFile = new File(cacheDir, fileName); if (imageFile.exists()) { Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath()); imageView.setImageBitmap(bitmap); } else { new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = downloadImage(url); if (bitmap != null) { saveImageToCache(imageFile, bitmap); handler.post(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } else { handler.post(new Runnable() { @Override public void run() { imageView.setImageResource(R.drawable.no_image_dow_http); } }); } } }).start(); } }
2. 下載圖片
downloadImage
方法使用 HttpURLConnection
從給定URL下載圖片。它設(shè)置了連接和讀取的超時(shí),以避免長時(shí)間等待。
private Bitmap downloadImage(String urlString) { Bitmap bitmap = null; try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } return bitmap; }
3. 保存圖片到緩存
saveImageToCache
方法將下載的圖片以PNG格式保存到應(yīng)用的緩存目錄中。
private void saveImageToCache(File imageFile, Bitmap bitmap) { try { OutputStream outputStream = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
4. 文件名提取
getFileNameFromUrl
方法從圖片URL中提取文件名,以便在緩存中使用。
private String getFileNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); }
或者通過學(xué)習(xí)glide
到此這篇關(guān)于在Android中高效管理圖片加載的文章就介紹到這了,更多相關(guān)Android圖片加載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 詳解Android?GLide圖片加載常用幾種方法
- Android圖片加載框架Coil的詳細(xì)使用總結(jié)
- Android 官推 kotlin-first 的圖片加載庫——Coil的使用入門
- Android編程圖片加載類ImageLoader定義與用法實(shí)例分析
- Android基于Glide v4.x的圖片加載進(jìn)度監(jiān)聽
- Android ListView實(shí)現(xiàn)ImageLoader圖片加載的方法
- Android中RecyclerView 滑動(dòng)時(shí)圖片加載的優(yōu)化
- Android圖片加載框架Glide的基本用法介紹
- Android圖片加載利器之Picasso基本用法
相關(guān)文章
Android 中clipToPadding 和 clipChildren區(qū)別和作用
這篇文章主要介紹了Android 中clipToPadding 和 clipChildren區(qū)別和作用的相關(guān)資料,需要的朋友可以參考下2017-06-06Android實(shí)現(xiàn)下載m3u8視頻文件問題解決
這篇文章主要介紹了Android實(shí)現(xiàn)下載m3u8視頻文件,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01android之計(jì)時(shí)器(Chronometer)的使用以及常用的方法
在Android的SDK中,為我們提供了一個(gè)計(jì)時(shí)器,這個(gè)計(jì)時(shí)器稱為Chronometer,我們可以成它為Android的一個(gè)組件,同時(shí)它也具備自己獨(dú)有的方法2013-01-01android開發(fā)環(huán)境中SDK文件夾下的所需內(nèi)容詳解
在本篇文章里小編給大家整理的是關(guān)于android開發(fā)環(huán)境中SDK文件夾下的所需內(nèi)容詳解,有興趣的朋友們參考學(xué)習(xí)下。2019-09-09Android屬性動(dòng)畫實(shí)現(xiàn)炫酷的登錄界面
這篇文章主要為大家詳細(xì)介紹了Android屬性動(dòng)畫實(shí)現(xiàn)炫酷的登錄界面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-07-07AndroidStudio利用android-support-multidex解決64k的各種異常
這篇文章主要為大家詳細(xì)介紹了AndroidStudio利用android-support-multidex解決64k的各種異常,感興趣的小伙伴們可以參考一下2016-09-09android listview實(shí)現(xiàn)新聞列表展示效果
這篇文章主要為大家詳細(xì)介紹了android listview實(shí)現(xiàn)新聞列表展示效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03淺扒Android動(dòng)態(tài)設(shè)置字體大小的示例
本篇文章主要介紹了淺扒Android動(dòng)態(tài)設(shè)置字體大小的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12