android編程實(shí)現(xiàn)圖片庫(kù)的封裝方法
本文實(shí)例講述了android編程實(shí)現(xiàn)圖片庫(kù)的封裝方法。分享給大家供大家參考,具體如下:
大家在做安卓應(yīng)用的時(shí)候 經(jīng)常要從網(wǎng)絡(luò)中獲取圖片 都是通過(guò)URL去獲取 可是如果本地有圖片數(shù)據(jù) 從本地獲取數(shù)據(jù)不更加快一些 自己在工作中遇到這個(gè)問(wèn)題 所以采用了一個(gè)URL和本地圖片的一個(gè)映射關(guān)系 先從本地區(qū)獲取 假如本地沒(méi)有再?gòu)木W(wǎng)絡(luò)中獲取 本方法考慮到多線程問(wèn)題 歡迎大家一起共同探討!
public class PictureLibrary {
/*
* 圖片庫(kù)的操作
*/
File file;
URL url;
HttpURLConnection conn;
InputStream is;
FileOutputStream fos;
private Lock lock = new ReentrantLock();
private Condition downFile = lock.newCondition();
// 通過(guò)URL將數(shù)據(jù)下載到本地操作
private String toLocalFile(String strURL) {
String fileName = Utils.getFileName(strURL);
String path = Environment.getExternalStorageDirectory() + "/"
+ EcologicalTourism.FILE_PATH + "/images/" + fileName;
return path;
}
// 通過(guò)URL將數(shù)據(jù)下載到本地臨時(shí)文件中
private String toLocalFileTemp(String strURL) {
String s = Utils.getFileName(strURL);
String fileName = s+"temp";
String path_url = Environment.getExternalStorageDirectory() + "/"
+ EcologicalTourism.FILE_PATH + "/tempimages/" + fileName;
return path_url;
}
/*
* 保存圖片到本地,并返回本地url(此函數(shù)是阻塞的)
* main
* @參數(shù):strURL,參數(shù)為圖片的URL.返回值:該圖片在本地SD卡暫存的位置
* 函數(shù)的工作是負(fù)責(zé)將圖片從互聯(lián)網(wǎng)上取得,存在本地存儲(chǔ)中,并返回本地存儲(chǔ)的文件路徑,供調(diào)用者直接使用。如果文件已經(jīng)存在本地,直接返回
* 如果文件未在本地,則直接從服務(wù)器下載,函數(shù)阻塞。
*/
public String getReadSD(String strURL) {
Log.i("test", "拿到網(wǎng)絡(luò)的地址是:" + strURL);
String strLocalFile = toLocalFile(strURL); //k:把服務(wù)器URL轉(zhuǎn)換為本地URL
String strLocalFileTemp = toLocalFileTemp(strURL); //k:把服務(wù)器URL轉(zhuǎn)換為本地臨時(shí)URL
while (true) {
File file = new File(strLocalFile);
Log.i("test", "本地文件是:" + strLocalFile);
File tfile = new File(strLocalFileTemp);
Log.i("test", "臨時(shí)文件是:" + strLocalFileTemp);
// 1上鎖
lock.lock();
if (file.exists()) {
// 2if 本地文件存在
// 解鎖
// 返回本地路徑
lock.unlock();
Log.i("test", "返回本地路徑:" + file);
return strLocalFile;
} else if (tfile.exists()) {
// if 對(duì)應(yīng)的暫存文件存在
// 解鎖
lock.unlock();
try {
// 睡眠
downFile.await();
} catch (Exception e) {
e.printStackTrace();
Log.i("test", "e 出現(xiàn)了異常1" + e);
}
} else {
try {
// 創(chuàng)建對(duì)應(yīng)的暫存文件
tfile.createNewFile();
} catch (IOException e) {
Log.i("test", "e 出現(xiàn)了異常2" + e);
}
// 解鎖
lock.unlock();
// 下載文件內(nèi)容到暫存文件中
downURL2(strURL, strLocalFile);
// 上鎖
lock.lock();
// 修改暫存文件名字為本地文件名
tfile.renameTo(file);
// 解鎖
lock.unlock();
}
}
}
private void downURL2(String strURL, String strLocalFileTemp) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(strLocalFileTemp);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
// 返回一個(gè)URI對(duì)象
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 阻塞式下載url到文件 toFile中
*/
private boolean downURL(String strURL, String toFile) {
URL url;
try {
url = new URL(strURL);
HttpURLConnection httpUrl = (HttpURLConnection) url
.openConnection();
httpUrl.setRequestMethod("GET");
int fileSize = httpUrl.getContentLength();// 文件大小
httpUrl.disconnect();// 關(guān)閉連接
int threadSize = 6;// 默認(rèn)設(shè)置6個(gè)線程
threadSize = fileSize % threadSize == 0 ? threadSize
: threadSize + 1;
int currentSize = fileSize / threadSize; // 每條線程下載大小
String dowloadir = Environment.getExternalStorageDirectory() + "/"
+ EcologicalTourism.FILE_PATH + "/images/";
File dir = new File(dowloadir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, toFile);
RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
randomFile.setLength(fileSize);// 指定 file 文件的大小
for (int i = 0; i < threadSize; i++) {
int startposition = i * currentSize;// 每條線程開始寫入文件的位置
RandomAccessFile threadFile = new RandomAccessFile(file, "rw");
Log.i("syso", "toFile的內(nèi)容是:" + toFile);
threadFile.seek(startposition);
new DownLoadThread(i, currentSize, threadFile, startposition,
url).start();
}
} catch (Exception e) {
e.printStackTrace();
Log.i("syso", "download下載失敗" + e);
}
return true;
}
/**
* 實(shí)現(xiàn)線程下載
*
*/
private static class DownLoadThread extends Thread {
@SuppressWarnings("unused")
private int threadId;// 線程編號(hào)
private int currentSize;// 每條線程的大小
private RandomAccessFile threadFile; // 每條線程 要寫入文件類
private int startposition;// 每條線程開始寫入文件的位置
private URL url; //網(wǎng)絡(luò)地址
public DownLoadThread(int threadId, int currentSize,
RandomAccessFile threadFile, int startposition, URL url) {
this.threadId = threadId;
this.currentSize = currentSize;
this.threadFile = threadFile;
this.startposition = startposition;
this.url = url;
}
public void run() {
try {
HttpURLConnection httpUrl = (HttpURLConnection) url
.openConnection();
httpUrl.setRequestMethod("GET");
httpUrl.setRequestProperty("range", "bytes=" + startposition
+ "-");// 指定服務(wù)器的位置
InputStream is = httpUrl.getInputStream();
byte[] data = new byte[1024];
int len = -1;
int threadFileSize = 0;
while ((threadFileSize < currentSize)
&& ((len = is.read(data)) != -1)) {
threadFile.write(data, 0, len);
threadFileSize += len;
}
httpUrl.disconnect();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 從本緩存中獲取圖片
*/
public Bitmap getBitmapFromCache(String imageURL) {
// String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1);
String bitmapName = Utils.getFileName(imageURL);
File cacheDir = new File(Environment.getExternalStorageDirectory() + "/"
+ EcologicalTourism.FILE_PATH + "/images/");
File[] cacheFiles = cacheDir.listFiles();
int i = 0;
if(null!=cacheFiles){
for(; i<cacheFiles.length;i++){
if(bitmapName.equals(cacheFiles[i].getName())){
break;
}
}
if(i < cacheFiles.length)
{
return BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/"
+ EcologicalTourism.FILE_PATH + "/images/" + bitmapName);
}
}
return null;
}
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android編程實(shí)現(xiàn)給Button添加圖片和文字的方法
- Android代碼實(shí)現(xiàn)圖片和文字上下布局
- android編程實(shí)現(xiàn)系統(tǒng)圖片剪裁的方法
- Android編程中圖片特效處理方法小結(jié)
- Android圖片轉(zhuǎn)換器代碼分享
- Android啟動(dòng)相機(jī)拍照并返回圖片
- Android編程之圖片顏色處理方法
- Android編程學(xué)習(xí)之異步加載圖片的方法
- android圖片類型之間相互轉(zhuǎn)換實(shí)現(xiàn)代碼
- Android實(shí)現(xiàn)ListView異步加載圖片的方法
- Android開發(fā)從相機(jī)或相冊(cè)獲取圖片裁剪
- Android編程之圖片相關(guān)代碼集錦
相關(guān)文章
Android viewpager自動(dòng)輪播和小圓點(diǎn)聯(lián)動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了Android viewpager自動(dòng)輪播和小圓點(diǎn)聯(lián)動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
Android中Service和Activity相互通信示例代碼
在android中Activity負(fù)責(zé)前臺(tái)界面展示,service負(fù)責(zé)后臺(tái)的需要長(zhǎng)期運(yùn)行的任務(wù)。下面這篇文章主要給大家介紹了關(guān)于Android中Service和Activity相互通信的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-09-09
Android開發(fā)實(shí)現(xiàn)Fragment監(jiān)聽返回鍵事件功能的方法
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)Fragment監(jiān)聽返回鍵事件功能的方法,結(jié)合實(shí)例形式分析了Android使用Fragment監(jiān)聽并屏蔽返回鍵按鈕的實(shí)現(xiàn)方法與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
Android打造屬于自己的新聞平臺(tái)(客戶端+服務(wù)器)
這篇文章主要為大家詳細(xì)介紹了Android打造屬于自己的新聞平臺(tái)的相關(guān)資料,Android實(shí)現(xiàn)新聞客戶端服務(wù)器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-06-06
Android編程之桌面小部件AppWidgetProvider用法示例
這篇文章主要介紹了Android編程之桌面小部件AppWidgetProvider用法,結(jié)合具體實(shí)例形式分析了Android桌面組件AppWidgetProvider的功能、布局、權(quán)限設(shè)置等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
Android實(shí)現(xiàn)微信加號(hào)菜單模式
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)微信加號(hào)菜單模式,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-08-08
Android實(shí)現(xiàn)雷達(dá)View效果的示例代碼
這篇文章主要介紹了Android實(shí)現(xiàn)雷達(dá)View效果,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
Android大作業(yè)功能設(shè)計(jì)之自動(dòng)登錄和記住密碼
SharedPreferences是Android平臺(tái)上一個(gè)輕量級(jí)的存儲(chǔ)類,主要是保存一些常用的配置參數(shù),它是采用xml文件存放數(shù)據(jù)的,文件存放在"/data/data<package?name>/shared_prefs"目錄下,由于SharedPreferences是一個(gè)接口,而且在這個(gè)接口里沒(méi)有提供寫入數(shù)據(jù)和讀取數(shù)據(jù)的能力2023-01-01

