android 怎么封装方法,android编程实现图片库的封装方法

本文实例讲述了android编程实现图片库的封装方法。分享给大家供大家参考,具体如下:

大家在做安卓应用的时候 经常要从网络中获取图片 都是通过URL去获取 可是如果本地有图片数据 从本地获取数据不更加快一些 自己在工作中遇到这个问题 所以采用了一个URL和本地图片的一个映射关系 先从本地区获取 假如本地没有再从网络中获取 本方法考虑到多线程问题 欢迎大家一起共同探讨!

public class PictureLibrary {

/*

* 图片库的操作

*/

File file;

URL url;

HttpURLConnection conn;

InputStream is;

FileOutputStream fos;

private Lock lock = new ReentrantLock();

private Condition downFile = lock.newCondition();

// 通过URL将数据下载到本地操作

private String toLocalFile(String strURL) {

String fileName = Utils.getFileName(strURL);

String path = Environment.getExternalStorageDirectory() + "/"

+ EcologicalTourism.FILE_PATH + "/images/" + fileName;

return path;

}

// 通过URL将数据下载到本地临时文件中

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(此函数是阻塞的)

* main

* @参数:strURL,参数为图片的URL.返回值:该图片在本地SD卡暂存的位置

* 函数的工作是负责将图片从互联网上取得,存在本地存储中,并返回本地存储的文件路径,供调用者直接使用。如果文件已经存在本地,直接返回

* 如果文件未在本地,则直接从服务器下载,函数阻塞。

*/

public String getReadSD(String strURL) {

Log.i("test", "拿到网络的地址是:" + strURL);

String strLocalFile = toLocalFile(strURL); //k:把服务器URL转换为本地URL

String strLocalFileTemp = toLocalFileTemp(strURL); //k:把服务器URL转换为本地临时URL

while (true) {

File file = new File(strLocalFile);

Log.i("test", "本地文件是:" + strLocalFile);

File tfile = new File(strLocalFileTemp);

Log.i("test", "临时文件是:" + strLocalFileTemp);

// 1上锁

lock.lock();

if (file.exists()) {

// 2if 本地文件存在

// 解锁

// 返回本地路径

lock.unlock();

Log.i("test", "返回本地路径:" + file);

return strLocalFile;

} else if (tfile.exists()) {

// if 对应的暂存文件存在

// 解锁

lock.unlock();

try {

// 睡眠

downFile.await();

} catch (Exception e) {

e.printStackTrace();

Log.i("test", "e 出现了异常1" + e);

}

} else {

try {

// 创建对应的暂存文件

tfile.createNewFile();

} catch (IOException e) {

Log.i("test", "e 出现了异常2" + e);

}

// 解锁

lock.unlock();

// 下载文件内容到暂存文件中

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();

// 返回一个URI对象

}

} 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();// 关闭连接

int threadSize = 6;// 默认设置6个线程

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的内容是:" + toFile);

threadFile.seek(startposition);

new DownLoadThread(i, currentSize, threadFile, startposition,

url).start();

}

} catch (Exception e) {

e.printStackTrace();

Log.i("syso", "download下载失败" + e);

}

return true;

}

/**

* 实现线程下载

*

*/

private static class DownLoadThread extends Thread {

@SuppressWarnings("unused")

private int threadId;// 线程编号

private int currentSize;// 每条线程的大小

private RandomAccessFile threadFile; // 每条线程 要写入文件类

private int startposition;// 每条线程开始写入文件的位置

private URL url; //网络地址

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

+ "-");// 指定服务器的位置

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

if(bitmapName.equals(cacheFiles[i].getName())){

break;

}

}

if(i < cacheFiles.length)

{

return BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/"

+ EcologicalTourism.FILE_PATH + "/images/" + bitmapName);

}

}

return null;

}

希望本文所述对大家Android程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值