1. 程式人生 > >安卓的視訊快取

安卓的視訊快取

專案中遇到視訊播放,需要載入網路url,不可能每次都進行網路載入,當然了,就需要用到我們的快取機制

AndroidVideoCache

AndroidVideoCache是一個視訊/音訊快取庫,利用本地代理實現了邊下邊播,使用起來非常簡單。

HttpProxyCacheServer是主要類,是一個代理伺服器,可以配置快取檔案的數量、快取檔案的大小、快取檔案的目錄和快取檔案命名演算法,檔案快取均基於LRU演算法,利用Builder來配置:

複製程式碼
//配置快取目錄
public Builder cacheDirectory(File file);

//配置快取檔案命名規則
public Builder fileNameGenerator(FileNameGenerator fileNameGenerator) ;

//配置快取檔案大小 public Builder maxCacheSize(long maxSize) ; //配置快取檔案數量 public Builder maxCacheFilesCount(int count) ;
複製程式碼

建議以單列模式將HttpProxyCacheServer存放於Application中:

複製程式碼
public class App extends Application {

    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        App app 
= (App) context.getApplicationContext(); return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy; } private HttpProxyCacheServer newProxy() { return new HttpProxyCacheServer(this); } }
複製程式碼

呼叫十分方便,只需要增加一行程式碼:

複製程式碼
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); HttpProxyCacheServer proxy = getProxy(); String proxyUrl = proxy.getProxyUrl(VIDEO_URL); videoView.setVideoPath(proxyUrl); } private HttpProxyCacheServer getProxy() { return App.getProxy(getApplicationContext()); }
最後視訊載入的 時候需要判斷是否快取,做一些比如緩衝進度條的隱藏等操作