先前作了一個小視頻的功能,裏面有播放多個視頻的功能,爲了效率,我加了視頻緩存功能;android
一方面耗費用戶的流量,另外一方面直接從本地播放要更流暢git
網上看資料,一個視頻緩存庫,使用起來很方便,還不錯,就分享給你們github
//視頻緩存 implementation 'com.danikula:videocache:2.7.1'
效果緩存
代碼:app
public class MainActivity extends AppCompatActivity { private static final int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1; String url = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"; VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); videoView = findViewById(R.id.videoView); //檢查版本是否大於M if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE); } else { Log.i("aaa", "權限已申請"); initVideo(); } } } private void initVideo() { HttpProxyCacheServer proxy = VideoApplication.getProxy(this); //1.咱們會將原始url註冊進去 // proxy.registerCacheListener(, bean.getVideo_url()); //2.咱們播放視頻的時候會調用如下代碼生成proxyUrl String proxyUrl = proxy.getProxyUrl(url); if (proxy.isCached(url)) { Log.i("aaaa", "已緩存"); } else { Log.i("aaaa", "未緩存"); } Log.i("aaaapath", proxyUrl); videoView.setVideoPath(proxyUrl); videoView.start(); videoView.findFocus(); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { initVideo(); } else { //"權限已拒絕"; } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
日誌:ide
這樣能夠在本地的磁盤裏找到視頻了ui
Application代碼:this
public class VideoApplication extends Application { @Override public void onCreate() { super.onCreate(); } private HttpProxyCacheServer proxy; public static HttpProxyCacheServer getProxy(Context context) { VideoApplication app = (VideoApplication) context.getApplicationContext(); return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy; } private HttpProxyCacheServer newProxy() { return new HttpProxyCacheServer.Builder(this) .maxCacheSize(1024 * 1024 * 1024) // 1 Gb for cache .fileNameGenerator(new MyFileNameGenerator()) .build(); } }
記住不要忘記了AndroidManifest權限url
<uses-permission android:name="android.permission.INTERNET" /> <!--用於寫入緩存數據到擴展存儲卡--> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.VIBRATE" />
代碼下載:spa
https://github.com/DickyQie/android-video/tree/video-cache
參考文檔(庫地址)
https://github.com/danikula/AndroidVideoCache
https://blog.csdn.net/zhqw_csdn/article/details/81514313