AndroidVideoCache实现边播边缓存功能

AndroidVideoCache 通过代理的策略实现一个中间层将我们的网络请求转移到本地实现的代理服务器上,这样我们真正请求的数据就会被代理拿到,这样代理一边向本地写入数据,一边根据我们需要的数据看是读网络数据还是读本地缓存数据再提供给我们,真正做到了数据的复用。

下面是使用方法:

首先在AS用户一行代码在gradle中导包

dependencies{

    complie ‘com.danikula:videocache:2,6.4'

}

然后在全局初始化一个本地代理服务器,这里选择在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);

    }

}

有了代理服务器,我们就可以使用了,把自己的网络视频url用提供的方法替换成另一个URL

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    HttpProxyCacheServer proxy = getProxy();

    String proxyUrl = proxy.getProxyUrl(VIDEO_URL);

    videoView.setVideoPath(proxyUrl);

}

这样就已经可以正常使用了,当然这个库提供了更多的可以自定义的地方,比如缓存的文件最大大小,以及文件个数,缓存采取的是LruCache的方法,对于老文件在达到上限后会自动清理。

private HttpProxyCacheServer newProxy() {

    return new HttpProxyCacheServer.Builder(this)

        .maxCacheSize(1024 * 1024 * 1024) // 1 Gb for cache

        .build();

}

private HttpProxyCacheServer newProxy() {

    return new HttpProxyCacheServer.Builder(this)

        .maxCacheFilesCount(20)

        .build();

}

除了这个,还有一个就是生成的文件名,默认是使用的MD5方式生成key,考虑到一些业务逻辑,我们也可以继承一个 FileNameGenerator 来实现自己的策略

public class MyFileNameGenerator implements FileNameGenerator {

    public String generate(String url) {

        Uri uri = Uri.parse(url);

        String videoId = uri.getQueryParameter("videoId");

        return videoId + ".mp4";

    }

}

...HttpProxyCacheServer proxy = HttpProxyCacheServer.Builder(context)   

        .fileNameGenerator(new MyFileNameGenerator())   

        .build()

猜你喜欢

转载自blog.csdn.net/qq_25017839/article/details/89634507