最近弄一个广告的功能,需要用到视频和图片下载。每次都去下载就会导致流量耗费比较多,就增添了一个视频和图片缓存的功能。
一、涉及到的开源代码
1、SmartImageView
1.1、功能和优点
SmartImageView主要是为了加速从网上加载图片,支持根据URL地址加载图片,支持异步加载图片,支持图片缓存等。
1.2、开源代码
https://github.com/JackCho/SmartImageView
https://github.com/loopj/android-smart-image-view
有一点点不一样,但是整体框架是一样的。
1.3、推荐博客
2、AndroidVideoCache
1.1、功能和优缺点
功能:视频播放和缓存。
优点:
1、使用简单,支持设置缓存视频的大小或个数;
2、支持断点缓存(一段视频缓存一部分后,退出关闭视频后,下次再看时会从上次缓存到的部分开始继续缓存);
缺点:
1、当快进视频时,如果视频没缓存到该位置,需要等视频缓存到这个点才会播放,不会直接跳到快进点开始缓存;
1.2、开源代码
1.3、推荐博客
二、通过okhttp下载保存文件
本来是想通过smartimagerview或者Androidvideocache一个开源库支持上缓存和显示的功能。
1、只使用smartimagerview,视频在线播放功能可能会打折扣
2、只使用Androidvideocache,Androidvideocache耦合很多,缓存功能开发难度大。
单独使用一个是不可能的,同时我所做的缓存并不需要打断功能,所以选择缓存文件直接使用简单下载保存就可以了。下面就是okhttp的文件下载保存代码。
import java.io.File;
import android.content.Context;
import com.seecool.apmservice.APMApplication;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import com.android.okhttp.OkHttpClient;
import com.android.okhttp.Request;
import com.android.okhttp.Call;
import com.android.okhttp.Callback;
import com.android.okhttp.Response;
import com.seecool.apmservice.util.StringUtils;
public class xxx{
private static final String DISK_CACHE_PATH = "/ad_cache/";
public void cache(String url) {
InputStream is = null;
FileOutputStream fos = null;
byte[] buf = new byte[2048];
int len = 0;
try {
long sum = 0;
File file = new File(getFilePath(), getCacheKey(url));
fos = new FileOutputStream(file);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = okHttpClient.newCall(request).execute();
is = response.body().byteStream();
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
}
fos.flush();
is.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
private String getCacheKey(String url) {
if(StringUtils.isEmptyOrNull(url)){
throw new RuntimeException("Null url passed in");
} else {
int slashIndex = url.lastIndexOf('/');
return url.substring(slashIndex+1,url.length());
//return url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+");
}
}
private String getFilePath() {
String diskCachePath;
Context appContext = APMApplication.getAppContext();
diskCachePath = appContext.getCacheDir().getAbsolutePath() + DISK_CACHE_PATH;
File file = new File(diskCachePath);
if (!file.exists()) {
file.mkdir();
}
return diskCachePath;
}
}
结束语
好的,今天的分享和总结就到这里,下一篇让我们看看倒计时怎么做,如果很简单或者博客比较多的话,我就不写了。