├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── gibbon │ │ └── videopreloadmanager │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── gibbon │ │ │ └── videopreloadmanager │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── gibbon │ └── videopreloadmanager │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images ├── device-2020-05-15-170554.gif ├── nullFile └── preload.jpg ├── settings.gradle └── videopreload ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src ├── androidTest └── java │ └── com │ └── gibbon │ └── videopreload │ └── ExampleInstrumentedTest.java ├── main ├── AndroidManifest.xml ├── java │ └── com │ │ └── gibbon │ │ └── videopreload │ │ ├── PlayerEnvironment.java │ │ ├── PreLoadManager.java │ │ ├── PreLoadTask.java │ │ ├── VideoPreLoadFuture.java │ │ ├── adapter │ │ ├── DefaultNetworkAdapter.java │ │ └── INetworkAdapter.java │ │ └── util │ │ ├── AndroidUtils.java │ │ └── StorageUtils.java └── res │ └── values │ └── strings.xml └── test └── java └── com └── gibbon └── videopreload └── ExampleUnitTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.aar 4 | *.ap_ 5 | *.aab 6 | 7 | # Files for the ART/Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | # Uncomment the following line in case you need and you don't have the release build type files in your app 18 | # release/ 19 | 20 | # Gradle files 21 | .gradle/ 22 | build/ 23 | 24 | # Local configuration file (sdk path, etc) 25 | local.properties 26 | 27 | # Proguard folder generated by Eclipse 28 | proguard/ 29 | 30 | # Log Files 31 | *.log 32 | 33 | # Android Studio Navigation editor temp files 34 | .navigation/ 35 | 36 | # Android Studio captures folder 37 | captures/ 38 | 39 | # IntelliJ 40 | *.iml 41 | .idea/workspace.xml 42 | .idea/tasks.xml 43 | .idea/gradle.xml 44 | .idea/assetWizardSettings.xml 45 | .idea/dictionaries 46 | .idea/libraries 47 | .idea/ 48 | # Android Studio 3 in .gitignore file. 49 | .idea/caches 50 | .idea/modules.xml 51 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 52 | .idea/navEditor.xml 53 | 54 | # Keystore files 55 | # Uncomment the following lines if you do not want to check your keystore files in. 56 | #*.jks 57 | #*.keystore 58 | 59 | # External native build folder generated in Android Studio 2.2 and later 60 | .externalNativeBuild 61 | .cxx/ 62 | 63 | # Google Services (e.g. APIs or Firebase) 64 | # google-services.json 65 | 66 | # Freeline 67 | freeline.py 68 | freeline/ 69 | freeline_project_description.json 70 | 71 | # fastlane 72 | fastlane/report.xml 73 | fastlane/Preview.html 74 | fastlane/screenshots 75 | fastlane/test_output 76 | fastlane/readme.md 77 | 78 | # Version control 79 | vcs.xml 80 | 81 | # lint 82 | lint/intermediates/ 83 | lint/generated/ 84 | lint/outputs/ 85 | lint/tmp/ 86 | # lint/reports/ 87 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VideoPreload 2 | 对AndroidVideoCache开源库的补充,支持预加载短视频数据的能力。 3 | AndroidVideoCache只支持边下边播以及缓存的能力,但是一般情况下,为了短视频首帧能秒出,以MP4为例,如果不提前预加载的数据的情况下,播放器需要先下载MP4格式的头部数据以及几帧数据之后才开始渲染,这其中无疑下载的耗时最大的决定了首帧出现的时间,从而在秒出效果上是有影响的。因此提前做预加载就显得有必要。 4 | 5 | #### 几个重要的类 6 | 考虑到一种场景如feed信息流中就不乏存在短视频,在点击某个短视频进入全屏页面的时候,一般也像抖音那样可以上下滑动列表的全屏列表页。 7 | 8 | 因此VideoPreload库涉及几个类: 9 | 10 | 1. VideoPreLoadFuture:每个需要用到短视频列表的页面需要初始化, 后续拿着该实例进行相应操作(如下两个方法) 11 | ``` 12 | /** 13 | * @param context 14 | * @param preloadBusId 每个页面对应一个preloadBusId 15 | / 16 | public VideoPreLoadFuture(Context context, String preloadBusId) 17 | // 增量添加视频列表 18 | public void addUrls(List urls); 19 | // 全量添加视频列表 20 | public void updateUrls(List urls); 21 | ``` 22 | 23 | 2. PreloadManager: 预加载VideoPreLoadFuture能力管理类 24 | ``` 25 | // 为方便管理,使用者可通过preloadBusId获取VideoPreLoadFuture实例,可选调用 26 | public VideoPreLoadFuture getVideoPreLoadFuture(String preloadBusId); 27 | 28 | /** 29 | *接入者的播放组件在开始播放的时候调用该方法,参数preloadBusId和VideoPreLoadFuture 30 | * 初始化的VideoPreLoadFuture保持一致,url为短视频播放地址 31 | */ 32 | public void currentVideoPlay(String preloadBusId, String url) 33 | ``` 34 | 35 | #### 接入例子 36 | 1. 在某个Activity或者Fragment下,初始化VideoPreLoadFuture 37 | ``` 38 | if (videoPreLoadFuture == null) { 39 | videoPreLoadFuture = new VideoPreLoadFuture(context, "test"); 40 | } 41 | ``` 42 | 2. 请求完短视频列表数据之后,进行增量或者全量设置视频url列表,用于预加载 43 | ``` 44 | videoPreLoadFuture.addUrls(Arrays.asList(PreloadManager.MOCK_DATA)); 45 | ``` 46 | 或 47 | ``` 48 | PreLoadManager.getInstance(context).getVideoPreLoadFuture("test").addUrls(Arrays.asList(PreloadManager.MOCK_DATA)); 49 | ``` 50 | 3. 在播放组件中,如XXXVideoView(一般情况,每个业务方都会有关于播放器的封装view)的开始播放方法如start方法设置当前正在播放的url, 51 | PreloadManager的currentVideoPlay会根据当前播放url对应所在url列表中的位置,进行附近url的提前预加载 52 | ``` 53 | public void start() { 54 | // 通过该方法可打印出对应url是否已经预加载完成并存在相关的数据 55 | if (PreloadManager.getInstance().hasEnoughCache(url)) { 56 | Log.d(PreloadManager.TAG, url + " has a cache"); 57 | } 58 | 59 | // 参数preloadBusId和VideoPreLoadFuture初始化的VideoPreLoadFuture保持一致,url为当前短视频播放地址 60 | PreloadManager.getInstance().currentVideoPlay(preloadBusId, url); 61 | } 62 | ``` 63 | 64 | 很简单的几步就可以完成短视频数据的预加载,而且也完美的配合AndroidVideoCache的能力 65 | 66 | #### 实现原理 67 | ![image](https://github.com/zhuozp/VideoPreload/blob/master/images/preload.jpg) 68 | 69 | #### 看个demo录屏 70 | 71 | ![示例](https://github.com/zhuozp/VideoPreload/blob/master/images/device-2020-05-15-170554.gif) 72 | 73 | #### 点个star 74 | 觉得不错的话还请点个赞呗,接下来将对不同网络环境下预加载的处理以及根据线上环境,来进一步优化预加载的逻辑 75 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 29 5 | defaultConfig { 6 | applicationId "com.gibbon.videopreloadmanager" 7 | minSdkVersion 15 8 | targetSdkVersion 29 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | implementation fileTree(dir: 'libs', include: ['*.jar']) 23 | implementation 'androidx.appcompat:appcompat:1.0.2' 24 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 25 | testImplementation 'junit:junit:4.12' 26 | androidTestImplementation 'androidx.test.ext:junit:1.1.0' 27 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 28 | } 29 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/gibbon/videopreloadmanager/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreloadmanager; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | 25 | assertEquals("com.gibbon.videopreloadmanager", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/gibbon/videopreloadmanager/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreloadmanager; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.os.Bundle; 6 | 7 | public class MainActivity extends AppCompatActivity { 8 | 9 | @Override 10 | protected void onCreate(Bundle savedInstanceState) { 11 | super.onCreate(savedInstanceState); 12 | setContentView(R.layout.activity_main); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | VideoPreloadManager 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/gibbon/videopreloadmanager/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreloadmanager; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | jcenter() 7 | 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.5.3' 11 | 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | google() 20 | jcenter() 21 | 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | 21 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed May 13 23:07:22 CST 2020 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /images/device-2020-05-15-170554.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/images/device-2020-05-15-170554.gif -------------------------------------------------------------------------------- /images/nullFile: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /images/preload.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/images/preload.jpg -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':videopreload' 2 | rootProject.name='VideoPreloadManager' 3 | -------------------------------------------------------------------------------- /videopreload/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /videopreload/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 29 5 | 6 | 7 | defaultConfig { 8 | minSdkVersion 19 9 | targetSdkVersion 29 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 14 | consumerProguardFiles 'consumer-rules.pro' 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | 24 | } 25 | 26 | dependencies { 27 | implementation fileTree(dir: 'libs', include: ['*.jar']) 28 | 29 | implementation 'androidx.appcompat:appcompat:1.0.2' 30 | testImplementation 'junit:junit:4.12' 31 | androidTestImplementation 'androidx.test.ext:junit:1.1.0' 32 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 33 | implementation 'com.danikula:videocache:2.7.1' 34 | 35 | implementation "androidx.lifecycle:lifecycle-runtime:2.0.0" 36 | implementation "androidx.lifecycle:lifecycle-extensions:2.0.0" 37 | implementation "androidx.lifecycle:lifecycle-common-java8:2.0.0" 38 | annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0" 39 | } 40 | -------------------------------------------------------------------------------- /videopreload/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuozp/VideoPreload/47de4b5a3122f166676a7fb3362c12922e2b3469/videopreload/consumer-rules.pro -------------------------------------------------------------------------------- /videopreload/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /videopreload/src/androidTest/java/com/gibbon/videopreload/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | 25 | assertEquals("com.gibbon.videopreload.test", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /videopreload/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/PlayerEnvironment.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload; 2 | 3 | import android.content.Context; 4 | import android.text.TextUtils; 5 | 6 | import com.danikula.videocache.HttpProxyCacheServer; 7 | import com.danikula.videocache.file.Md5FileNameGenerator; 8 | import com.gibbon.videopreload.util.StorageUtils; 9 | 10 | import java.io.File; 11 | 12 | /** 13 | * @author zhipeng.zhuo 14 | * @date 2020-05-13 15 | */ 16 | public class PlayerEnvironment { 17 | 18 | private static HttpProxyCacheServer proxy; 19 | 20 | public static final String VIDEO_CACHE_ID = "videoCacheId"; 21 | 22 | public static HttpProxyCacheServer getProxy(Context context) { 23 | return proxy == null ? (proxy = newProxy(context)) : proxy; 24 | } 25 | 26 | private static HttpProxyCacheServer newProxy(Context context) { 27 | return new HttpProxyCacheServer.Builder(context.getApplicationContext()) 28 | .build(); 29 | } 30 | 31 | 32 | 33 | private static String path; 34 | 35 | public static String getCompleteCachePath(Context context, String url) { 36 | try { 37 | if (TextUtils.isEmpty(path)) { 38 | File cacheRoot = StorageUtils.getIndividualCacheDirectory(context); 39 | path = cacheRoot.getAbsolutePath(); 40 | } 41 | String name = new Md5FileNameGenerator().generate(url); 42 | if(TextUtils.isEmpty(name)){ 43 | return null; 44 | } 45 | File file = new File(path, name); 46 | if (file.exists() && file.canRead() && file.length() > 1024) { 47 | return file.getAbsolutePath(); 48 | } 49 | } catch (Throwable e) { 50 | } 51 | return null; 52 | } 53 | 54 | 55 | 56 | 57 | public static String getCachePathForCacheKey(Context context, String cacheKey) { 58 | try { 59 | if (TextUtils.isEmpty(cacheKey) || context == null) { 60 | return null; 61 | } 62 | if (TextUtils.isEmpty(path)) { 63 | File cacheRoot = StorageUtils.getIndividualCacheDirectory(context); 64 | path = cacheRoot.getAbsolutePath(); 65 | } 66 | 67 | File file = new File(path, cacheKey); 68 | if (file.exists() && file.canRead() && file.length() > 1024) { 69 | return file.getAbsolutePath(); 70 | } 71 | } catch (Throwable e) { 72 | } 73 | return null; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/PreLoadManager.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload; 2 | 3 | 4 | import android.content.Context; 5 | import android.os.Build; 6 | import android.os.Handler; 7 | import android.text.TextUtils; 8 | import android.util.ArrayMap; 9 | import android.util.Log; 10 | 11 | import androidx.annotation.RequiresApi; 12 | 13 | import com.danikula.videocache.HttpProxyCacheServer; 14 | import com.danikula.videocache.file.Md5FileNameGenerator; 15 | import com.gibbon.videopreload.util.AndroidUtils; 16 | 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.Stack; 20 | 21 | /** 22 | * @author zhipeng.zhuo 23 | * @date 2020-05-09 24 | */ 25 | @RequiresApi(api = Build.VERSION_CODES.KITKAT) 26 | public class PreLoadManager { 27 | 28 | public static final String TAG = PreLoadManager.class.getSimpleName(); 29 | 30 | public Stack mBusIdStack = new Stack<>(); 31 | public ArrayMap videoPreLoadFutureArrayMap = new ArrayMap<>(); 32 | public List preLoadTaskPool = new ArrayList<>(); 33 | 34 | public String currentBusId; 35 | 36 | public HttpProxyCacheServer httpProxyCacheServer; 37 | public Md5FileNameGenerator fileNameGenerator; 38 | public Context context; 39 | public Handler handler; 40 | 41 | private static volatile PreLoadManager sInstance; 42 | 43 | public static final String[] MOCK_DATA = { 44 | "30002464111", 45 | "30002248304", 46 | "30001730420", 47 | "30002202143", 48 | "30000996828", 49 | "30002168746", 50 | "30002096723", 51 | "30002532679", 52 | "30002532677", 53 | "30002532667", 54 | "30002532661", 55 | "30002532652", 56 | "30002532645", 57 | "30002532631", 58 | "30002532630", 59 | "30002532613", 60 | "30002532610", 61 | "30002532604", 62 | "30002532599", 63 | "30002532594", 64 | "30002532587", 65 | "30002532586", 66 | "30002532585", 67 | "30002532584", 68 | "30002532575", 69 | "30002532574", 70 | "30002532567", 71 | "30002532566", 72 | "30002532559", 73 | "30002532558", 74 | "30002532556", 75 | "30002532549", 76 | "30002532541", 77 | "30002532539", 78 | "30002532533", 79 | "30002532532", 80 | "30002532529", 81 | }; 82 | 83 | private PreLoadManager(Context context) { 84 | httpProxyCacheServer = PlayerEnvironment.getProxy(context); 85 | fileNameGenerator = new Md5FileNameGenerator(); 86 | this.context = context; 87 | } 88 | 89 | public static PreLoadManager getInstance(Context context) { 90 | if (sInstance == null) { 91 | synchronized (PreLoadManager.class) { 92 | if (sInstance == null) { 93 | sInstance = new PreLoadManager(context); 94 | } 95 | } 96 | } 97 | 98 | return sInstance; 99 | } 100 | 101 | 102 | protected void putFuture(String busId, VideoPreLoadFuture videoPreLoadFuture) { 103 | videoPreLoadFutureArrayMap.put(busId, videoPreLoadFuture); 104 | } 105 | 106 | protected void removeFuture(String busId) { 107 | videoPreLoadFutureArrayMap.remove(busId); 108 | } 109 | 110 | public VideoPreLoadFuture getVideoPreLoadFuture(String busId) { 111 | return videoPreLoadFutureArrayMap.get(busId); 112 | } 113 | 114 | public void currentVideoPlay(String busId, String url) { 115 | if (TextUtils.isEmpty(busId) || TextUtils.isEmpty(url)) { 116 | return; 117 | } 118 | 119 | VideoPreLoadFuture videoPreLoadFuture = getVideoPreLoadFuture(busId); 120 | 121 | if (videoPreLoadFuture != null) { 122 | videoPreLoadFuture.currentPlayUrl(url); 123 | } 124 | } 125 | 126 | public boolean hasEnoughCache(String url) { 127 | return AndroidUtils.hasEnoughCache(context, fileNameGenerator, url); 128 | } 129 | 130 | protected synchronized PreLoadTask createTask(final String busId, String url, int index) { 131 | PreLoadTask preLoadTask = null; 132 | if (preLoadTaskPool.size() > 0) { 133 | preLoadTask = preLoadTaskPool.get(0); 134 | preLoadTaskPool.remove(0); 135 | Log.d(TAG, "get PreLoadTask from pool"); 136 | } 137 | 138 | if (preLoadTask == null) { 139 | preLoadTask = new PreLoadTask(context, url, index); 140 | Log.d(TAG, "new PreLoadTask"); 141 | final PreLoadTask tmpPreLoadTask = preLoadTask; 142 | preLoadTask.setiTaskCallback(new PreLoadTask.ITaskCallback() { 143 | @Override 144 | public void finish() { 145 | VideoPreLoadFuture videoPreLoadFuture = getVideoPreLoadFuture(busId); 146 | if (videoPreLoadFuture != null) { 147 | videoPreLoadFuture.removeTask(tmpPreLoadTask); 148 | } 149 | recyclerPreLoadTask(tmpPreLoadTask); 150 | } 151 | }); 152 | } else { 153 | preLoadTask.init(url, index); 154 | } 155 | 156 | return preLoadTask; 157 | } 158 | 159 | protected synchronized void recyclerPreLoadTask(PreLoadTask task) { 160 | if (preLoadTaskPool.size() <= 20) { 161 | Log.d(TAG, "recycler PreLoadTask into pool"); 162 | preLoadTaskPool.add(task); 163 | } 164 | } 165 | 166 | protected String getLocalUrlAppendWithUrl(String url) { 167 | if (httpProxyCacheServer != null) { 168 | return httpProxyCacheServer.getProxyUrl(url); 169 | } 170 | 171 | return url; 172 | } 173 | } 174 | 175 | 176 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/PreLoadTask.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload; 2 | 3 | 4 | import android.content.Context; 5 | import android.text.TextUtils; 6 | import android.util.Log; 7 | 8 | import androidx.annotation.Nullable; 9 | 10 | import com.gibbon.videopreload.util.AndroidUtils; 11 | 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.net.URL; 15 | import java.net.URLConnection; 16 | import java.util.concurrent.TimeUnit; 17 | import java.util.concurrent.locks.Condition; 18 | import java.util.concurrent.locks.ReentrantLock; 19 | 20 | /** 21 | * @author zhipeng.zhuo 22 | * @date 2020-05-14 23 | */ 24 | public class PreLoadTask implements Runnable { 25 | 26 | public static final int STATUS_INIT = 0; 27 | public static final int STATUS_PRELOADING = 1; 28 | public static final int STATUS_LOADING = 2; 29 | public static final int STATUS_COMPLETED = 3; 30 | public static final int STATUS_CANCEL = 4; 31 | 32 | private volatile int status = STATUS_INIT; 33 | public volatile String url; 34 | public volatile int index; 35 | private volatile String cacheKey; 36 | 37 | private Context context; 38 | private long startTime; 39 | 40 | private ITaskCallback iTaskCallback; 41 | private ReentrantLock lock = new ReentrantLock(); 42 | private Condition waitCondition = lock.newCondition(); 43 | 44 | public PreLoadTask(Context context, final String url, final int index) { 45 | this.context = context; 46 | this.url = url; 47 | this.index = index; 48 | if (!TextUtils.isEmpty(url)) { 49 | this.cacheKey = AndroidUtils.textToMD5(url); 50 | } 51 | } 52 | 53 | public void init(String url, int index) { 54 | lock.lock(); 55 | try { 56 | this.url = url; 57 | this.index = index; 58 | this.cacheKey = AndroidUtils.textToMD5(url); 59 | this.status = STATUS_INIT; 60 | } finally { 61 | lock.unlock(); 62 | } 63 | } 64 | 65 | public void setiTaskCallback(ITaskCallback callback) { 66 | this.iTaskCallback = callback; 67 | } 68 | 69 | public void setStatus(int status) { 70 | lock.lock(); 71 | try { 72 | this.status = status; 73 | Log.d("TTTT", "status change1 " + this.status + " index: " + index); 74 | } finally { 75 | lock.unlock(); 76 | } 77 | } 78 | 79 | public void run() { 80 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + "----task run begin----"); 81 | if (status == STATUS_CANCEL) { 82 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + " has cancel"); 83 | finish(); 84 | return; 85 | } 86 | 87 | if (TextUtils.isEmpty(this.url)) { 88 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + " url is empty"); 89 | finish(); 90 | return; 91 | } 92 | 93 | status = STATUS_PRELOADING; 94 | preload(); 95 | 96 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + "----task run end----"); 97 | } 98 | 99 | private void preload() { 100 | if (status != STATUS_PRELOADING) { 101 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + "preload() " + "status is: " + status); 102 | return; 103 | } 104 | 105 | if (PreLoadManager.getInstance(context).hasEnoughCache(this.url)) { 106 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + "videoId " + url + " has enough cache"); 107 | finish(); 108 | return; 109 | } 110 | 111 | InputStream inputStream = null; 112 | long start = System.currentTimeMillis(); 113 | boolean flag = false; 114 | try { 115 | URL url = new URL(PreLoadManager.getInstance(context).getLocalUrlAppendWithUrl(this.url)); 116 | URLConnection urlConnection = url.openConnection(); 117 | urlConnection.setRequestProperty("Range","bytes=0-204799"); 118 | urlConnection.setConnectTimeout(5000); 119 | urlConnection.connect(); 120 | 121 | inputStream = urlConnection.getInputStream(); 122 | status = STATUS_LOADING; 123 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + "PreLoadTask run: loading" ); 124 | int bufferSize = 1024; 125 | byte[] buffer = new byte[bufferSize]; 126 | int length = 0; 127 | int tmp = 0; 128 | while (status == STATUS_LOADING && (tmp = inputStream.read(buffer)) != -1) { 129 | //Since we just need to kick start the prefetching, dont need to do anything here 130 | // or we can use ByteArrayOutputStream to write down the data to disk 131 | length += tmp; 132 | // Log.d(PreloadManager.TAG, Thread.currentThread().getName() + " downloaded length: " + length + ""); 133 | if (!flag) { 134 | Log.d("TTTT", "status change2: " + status + " index: " + index); 135 | flag = true; 136 | } 137 | 138 | if (length >= 102400) { 139 | status = STATUS_COMPLETED; 140 | } 141 | } 142 | 143 | if (status == STATUS_CANCEL) { 144 | Log.d("TTTT", Thread.currentThread().getName() + "task cancel!"); 145 | } 146 | 147 | inputStream.close(); 148 | } catch (IOException e) { 149 | Log.d(PreLoadManager.TAG, e.getMessage() + ""); 150 | } catch (Exception e) { 151 | Log.d(PreLoadManager.TAG, e.getMessage() + ""); 152 | } finally { 153 | Log.d(PreLoadManager.TAG, Thread.currentThread().getName() + "preload video url [url: " + PreLoadTask.this.url + ", time: " 154 | + (System.currentTimeMillis() - start) + "ms, index: " + PreLoadTask.this.index + ", status: " + this.status + "]"); 155 | 156 | finish(); 157 | } 158 | 159 | } 160 | 161 | private void finish() { 162 | if (iTaskCallback != null) { 163 | iTaskCallback.finish(); 164 | } 165 | } 166 | 167 | @Override 168 | public boolean equals(@Nullable Object obj) { 169 | if (obj instanceof PreLoadTask) { 170 | // Log.d(PreloadManager.TAG, "equals [" + this.url + ", " + ((PreLoadTask)obj).url + "]"); 171 | return !TextUtils.isEmpty(this.url) && this.url.equals(((PreLoadTask)obj).url); 172 | } 173 | 174 | // Log.d(PreloadManager.TAG, "two PreLoadTask not equal"); 175 | return false; 176 | } 177 | 178 | /** 179 | * 此处没涉及map/set操作,涉及需要重写该方法 180 | * */ 181 | @Override 182 | public int hashCode() { 183 | return super.hashCode(); 184 | } 185 | 186 | interface ITaskCallback { 187 | void finish(); 188 | } 189 | } 190 | 191 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/VideoPreLoadFuture.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload; 2 | 3 | import android.app.Application; 4 | import android.content.BroadcastReceiver; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.content.IntentFilter; 8 | import android.net.ConnectivityManager; 9 | import android.net.NetworkInfo; 10 | import android.os.Handler; 11 | import android.os.Message; 12 | import android.text.TextUtils; 13 | import android.util.Log; 14 | 15 | import androidx.lifecycle.Lifecycle; 16 | import androidx.lifecycle.LifecycleObserver; 17 | import androidx.lifecycle.LifecycleOwner; 18 | import androidx.lifecycle.OnLifecycleEvent; 19 | 20 | import com.gibbon.videopreload.adapter.DefaultNetworkAdapter; 21 | import com.gibbon.videopreload.adapter.INetworkAdapter; 22 | 23 | import java.lang.ref.WeakReference; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | import java.util.concurrent.ExecutorService; 27 | import java.util.concurrent.Executors; 28 | import java.util.concurrent.LinkedBlockingDeque; 29 | import java.util.concurrent.locks.Condition; 30 | import java.util.concurrent.locks.ReentrantLock; 31 | 32 | /** 33 | * @author zhipeng.zhuo 34 | * @date 2020-04-26 35 | */ 36 | public class VideoPreLoadFuture implements LifecycleObserver { 37 | 38 | private volatile List mUrls; 39 | private String mBusId; 40 | private String mCurrentUrl; 41 | private volatile int mCurrentIndex; 42 | private volatile boolean toPreLoad = false; 43 | private ReentrantLock mLock = new ReentrantLock(); 44 | private Condition empty = mLock.newCondition(); 45 | private Condition network = mLock.newCondition(); 46 | private LinkedBlockingDeque mLoadingTaskDeque = new LinkedBlockingDeque<>(); 47 | private ExecutorService mExecutorService = Executors.newCachedThreadPool(); 48 | private ConsumerThread mConsumerThread; 49 | private CurrentLoadingHandler mHandler; 50 | private Context mContext; 51 | private INetworkAdapter mNetworkAdapter; 52 | private BroadcastReceiver mNetworkReceiver; 53 | private volatile boolean mIsWifi = false; 54 | 55 | /** 56 | * @param context 57 | * @param preloadBusId 每个页面对应一个busId 58 | * */ 59 | public VideoPreLoadFuture(Context context, String preloadBusId) { 60 | mContext = context; 61 | mHandler = new CurrentLoadingHandler(this); 62 | 63 | if (context instanceof Application) { 64 | throw new RuntimeException("context should not be an Application"); 65 | } 66 | 67 | if (context instanceof LifecycleOwner) { 68 | ((LifecycleOwner) context).getLifecycle().addObserver(this); 69 | } 70 | 71 | if (TextUtils.isEmpty(preloadBusId)) { 72 | throw new RuntimeException("busId should not be empty"); 73 | } 74 | 75 | this.mBusId = preloadBusId; 76 | 77 | PreLoadManager.getInstance(context).putFuture(mBusId, this); 78 | 79 | setNetworkAdapter(new DefaultNetworkAdapter()); 80 | 81 | if (mNetworkReceiver == null) { 82 | mNetworkReceiver = new NetworkBroadcastReceiver(); 83 | } 84 | 85 | if (mContext != null) { 86 | try { 87 | mContext.registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 88 | } catch (Exception e) { 89 | Log.e(PreLoadManager.TAG, this + "\tregisterReceiver exp:" + e); 90 | } 91 | } 92 | 93 | mConsumerThread = new ConsumerThread(); 94 | mConsumerThread.start(); 95 | } 96 | 97 | public void setNetworkAdapter(INetworkAdapter networkAdapter) { 98 | mNetworkAdapter = networkAdapter; 99 | } 100 | 101 | public void addUrls(List urls) { 102 | mLock.lock(); 103 | try { 104 | if (this.mUrls == null) { 105 | this.mUrls = new ArrayList<>(); 106 | } 107 | 108 | this.mUrls.addAll(urls); 109 | } finally { 110 | mLock.unlock(); 111 | } 112 | } 113 | 114 | public void updateUrls(List urls) { 115 | mLock.lock(); 116 | try { 117 | if (this.mUrls != null) { 118 | this.mUrls.clear(); 119 | this.mUrls.addAll(urls); 120 | } else { 121 | this.mUrls = urls; 122 | } 123 | } finally { 124 | mLock.unlock(); 125 | } 126 | } 127 | 128 | private boolean hasPause = false; 129 | 130 | @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) 131 | public void onPause() { 132 | /** 133 | * 线程进入阻塞 134 | * */ 135 | Log.d(PreLoadManager.TAG, "onPause: "); 136 | 137 | if (mNetworkReceiver != null) { 138 | try { 139 | if (mContext != null) { 140 | mContext.unregisterReceiver(mNetworkReceiver); 141 | } 142 | } catch (Exception e) { 143 | Log.e(PreLoadManager.TAG, this + "\tunregisterReceiver exp:" + e); 144 | } 145 | } 146 | 147 | mLock.lock(); 148 | hasPause = true; 149 | try { 150 | PreLoadTask task; 151 | while ((task = mLoadingTaskDeque.poll()) != null) { 152 | task.setStatus(PreLoadTask.STATUS_CANCEL); 153 | } 154 | } catch (Exception e) { 155 | Log.e(PreLoadManager.TAG, "onPause: " + e.getMessage()); 156 | } finally { 157 | mLock.unlock(); 158 | } 159 | } 160 | 161 | @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) 162 | public void onResume() { 163 | /** 164 | * 唤醒进入阻塞的线程 165 | * */ 166 | Log.d(PreLoadManager.TAG, "onResume: "); 167 | 168 | if (mNetworkReceiver == null) { 169 | mNetworkReceiver = new NetworkBroadcastReceiver(); 170 | } 171 | 172 | if (mContext != null) { 173 | try { 174 | mContext.registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 175 | } catch (Exception e) { 176 | Log.e(PreLoadManager.TAG, this + "\tregisterReceiver exp:" + e); 177 | } 178 | } 179 | 180 | mLock.lock(); 181 | try { 182 | if (hasPause && !TextUtils.isEmpty(mCurrentUrl)) { 183 | toPreLoad = true; 184 | hasPause = false; 185 | Log.d(PreLoadManager.TAG, "ConsumerThread is notified"); 186 | empty.signal(); 187 | } 188 | } catch (Exception e) { 189 | Log.e(PreLoadManager.TAG, "onResume: " + e.getMessage()); 190 | } finally { 191 | mLock.unlock(); 192 | } 193 | } 194 | 195 | @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 196 | public void onDestroy() { 197 | Log.d(PreLoadManager.TAG, "onDestroy: "); 198 | PreLoadManager.getInstance(mContext).removeFuture(mBusId); 199 | /** 200 | * 关闭线程 201 | * */ 202 | if (mConsumerThread != null && !mConsumerThread.isInterrupted()) { 203 | mLock.lock(); 204 | try { 205 | mConsumerThread.interrupt(); 206 | mCurrentIndex = -1; 207 | empty.signal(); 208 | PreLoadTask task; 209 | while ((task = mLoadingTaskDeque.poll()) != null) { 210 | task.setStatus(PreLoadTask.STATUS_CANCEL); 211 | } 212 | } catch (Exception e) { 213 | Log.e(PreLoadManager.TAG, "onDestroy: " + e.getMessage()); 214 | } finally { 215 | mLock.unlock(); 216 | } 217 | } 218 | } 219 | 220 | public void currentPlayUrl(String url) { 221 | mHandler.removeMessages(CurrentLoadingHandler.MSG_SET); 222 | Message message = Message.obtain(); 223 | message.what = CurrentLoadingHandler.MSG_SET; 224 | message.obj = url; 225 | mHandler.sendMessage(message); 226 | } 227 | 228 | private void innerCurrentPlayUrl(String url) { 229 | mLock.lock(); 230 | try { 231 | if (mUrls == null || mUrls.size() <= 0) { 232 | throw new RuntimeException("url list should not be empty"); 233 | } 234 | 235 | if (!mUrls.contains(url)) { 236 | return; 237 | } 238 | 239 | mCurrentUrl = url; 240 | int currentIndex = mUrls.indexOf(url); 241 | if (currentIndex != - 1 && currentIndex != mCurrentIndex) { 242 | Log.d(PreLoadManager.TAG, "currentPlayUrl: [url: " + url + ", index: " + currentIndex + "]"); 243 | mCurrentIndex = currentIndex; 244 | toPreLoad = true; 245 | // notify 246 | Log.d(PreLoadManager.TAG, "ConsumerThread is notified"); 247 | empty.signal(); 248 | } 249 | } catch (Exception e) { 250 | Log.e(PreLoadManager.TAG, "currentPlayUrl: " + e.getMessage()); 251 | } finally { 252 | mLock.unlock(); 253 | } 254 | } 255 | 256 | private boolean isNetWorkConnect() { 257 | if (mContext == null) { 258 | return false; 259 | } 260 | ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 261 | NetworkInfo netInfo = cm.getActiveNetworkInfo(); 262 | boolean isConnect = (netInfo != null && netInfo.isConnected()); 263 | return isConnect; 264 | } 265 | 266 | class ConsumerThread extends Thread { 267 | 268 | @Override 269 | public void run() { 270 | mLock.lock(); 271 | try { 272 | while (!isInterrupted()) { 273 | if (!isNetWorkConnect() || (!mIsWifi && !mNetworkAdapter.canPreLoadIfNotWifi())) { 274 | Log.d(PreLoadManager.TAG, "ConsumerThread is await for" + (isNetWorkConnect() ? " is not wifi " : " network not connect")); 275 | network.await(); 276 | } 277 | 278 | if (!toPreLoad) { 279 | Log.d(PreLoadManager.TAG, "ConsumerThread is await"); 280 | empty.await(); 281 | } 282 | 283 | if (mCurrentIndex == -1) { 284 | continue; 285 | } 286 | /** 287 | * 默认加入队列为 288 | * 【max(mCurrentIndex - 3, 0), min(mCurrentIndex + 4, mUrls.size()-1 )] 289 | * */ 290 | Log.d(PreLoadManager.TAG, "Consumer thread current index is: " + mCurrentIndex); 291 | int firstIndex = Math.max(0, mCurrentIndex - 3); 292 | int lastIndex = Math.min(mCurrentIndex + 4, mUrls.size() - 1); 293 | PreLoadTask preLoadTask = null; 294 | String url; 295 | for (int i = firstIndex; i <= lastIndex; i++) { 296 | 297 | if (i == mCurrentIndex) { 298 | continue; 299 | } 300 | 301 | url = mUrls.get(i); 302 | if (TextUtils.isEmpty(url)) { 303 | continue; 304 | } 305 | preLoadTask = PreLoadManager.getInstance(mContext).createTask(mBusId, url, i); 306 | if (!mLoadingTaskDeque.contains(preLoadTask)) { 307 | if (mLoadingTaskDeque.size() >= 16) { 308 | PreLoadTask ingPreLoadTask = mLoadingTaskDeque.pollLast(); 309 | ingPreLoadTask.setStatus(PreLoadTask.STATUS_CANCEL); 310 | Log.d(PreLoadManager.TAG, "mLoadingTaskDeque size more than 16, remove index: " + ingPreLoadTask.index); 311 | } 312 | 313 | Log.d(PreLoadManager.TAG, "Put into mLoadingTaskDeque: " + preLoadTask.url); 314 | mLoadingTaskDeque.addFirst(preLoadTask); 315 | mExecutorService.submit(preLoadTask); 316 | } else { 317 | mLoadingTaskDeque.remove(preLoadTask); 318 | mLoadingTaskDeque.addFirst(preLoadTask); 319 | } 320 | } 321 | 322 | toPreLoad = false; 323 | } 324 | } catch (InterruptedException e) { 325 | e.printStackTrace(); 326 | } finally { 327 | Log.d(PreLoadManager.TAG, "ConsumerThread is finish"); 328 | mLock.unlock(); 329 | } 330 | } 331 | } 332 | 333 | public void removeTask(PreLoadTask task) { 334 | mLock.lock(); 335 | try { 336 | boolean flag = mLoadingTaskDeque.remove(task); 337 | Log.d(PreLoadManager.TAG, "removeTask " + (flag ? "success" : "fail")); 338 | } finally { 339 | mLock.unlock(); 340 | } 341 | } 342 | 343 | public class NetworkBroadcastReceiver extends BroadcastReceiver { 344 | 345 | @Override 346 | public void onReceive(Context context, Intent intent) { 347 | ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 348 | NetworkInfo netInfo = cm.getActiveNetworkInfo(); 349 | boolean isConnect = (netInfo != null && netInfo.isConnected()); 350 | if (isConnect) { 351 | int networkType = netInfo.getType(); 352 | if (networkType == ConnectivityManager.TYPE_WIFI) { 353 | mLock.lock(); 354 | try { 355 | mIsWifi = true; 356 | network.signal(); 357 | } finally { 358 | mLock.unlock(); 359 | } 360 | } else { 361 | mIsWifi = false; 362 | } 363 | } else { 364 | mIsWifi = false; 365 | } 366 | } 367 | } 368 | 369 | 370 | private static class CurrentLoadingHandler extends Handler { 371 | 372 | private static final int MSG_SET = 100; 373 | 374 | private WeakReference videoPreLoadFutureWeakReference; 375 | 376 | public CurrentLoadingHandler(VideoPreLoadFuture videoPreLoadFuture) { 377 | videoPreLoadFutureWeakReference = new WeakReference<>(videoPreLoadFuture); 378 | } 379 | 380 | @Override 381 | public void handleMessage(Message msg) { 382 | 383 | VideoPreLoadFuture videoPreLoadFuture = videoPreLoadFutureWeakReference.get(); 384 | 385 | if (videoPreLoadFuture == null) { 386 | return; 387 | } 388 | 389 | switch (msg.what) { 390 | case MSG_SET: 391 | if (msg.obj instanceof String) { 392 | videoPreLoadFuture.innerCurrentPlayUrl((String) msg.obj); 393 | } 394 | break; 395 | default: 396 | break; 397 | } 398 | } 399 | } 400 | } 401 | 402 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/adapter/DefaultNetworkAdapter.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload.adapter; 2 | 3 | /** 4 | * @author zhipeng.zhuo 5 | * @date 2020-06-18 6 | */ 7 | public class DefaultNetworkAdapter implements INetworkAdapter { 8 | @Override 9 | public boolean canPreLoadIfNotWifi() { 10 | return false; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/adapter/INetworkAdapter.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload.adapter; 2 | 3 | /** 4 | * @author zhipeng.zhuo 5 | * @date 2020-06-18 6 | */ 7 | public interface INetworkAdapter { 8 | boolean canPreLoadIfNotWifi(); 9 | } 10 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/util/AndroidUtils.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload.util; 2 | 3 | import android.content.Context; 4 | import android.net.Uri; 5 | import android.text.TextUtils; 6 | 7 | import com.danikula.videocache.file.Md5FileNameGenerator; 8 | import com.gibbon.videopreload.PlayerEnvironment; 9 | 10 | import java.io.File; 11 | import java.security.MessageDigest; 12 | import java.security.NoSuchAlgorithmException; 13 | 14 | /** 15 | * @author zhipeng.zhuo 16 | * @date 2020-05-14 17 | */ 18 | public class AndroidUtils { 19 | 20 | public static String textToMD5(String plainText) { 21 | try { 22 | MessageDigest md = MessageDigest.getInstance("MD5"); 23 | md.update(plainText.getBytes()); 24 | byte[] b = md.digest(); 25 | 26 | int i; 27 | 28 | StringBuilder buf = new StringBuilder(); 29 | for (final byte b1 : b) { 30 | i = b1; 31 | if (i < 0) 32 | i += 256; 33 | if (i < 16) 34 | buf.append("0"); 35 | buf.append(Integer.toHexString(i)); 36 | } 37 | return buf.toString(); 38 | } catch (NoSuchAlgorithmException e) { 39 | return null; 40 | } 41 | 42 | } 43 | 44 | public static final String TEMP_POSTFIX = ".download"; 45 | 46 | public static boolean hasEnoughCache(Context context, Md5FileNameGenerator generator, String url) { 47 | try { 48 | File cacheRoot = StorageUtils.getIndividualCacheDirectory(context); 49 | String path = cacheRoot.getAbsolutePath(); 50 | 51 | String name = generator.generate(url); 52 | if(TextUtils.isEmpty(name)){ 53 | return false; 54 | } 55 | File file = new File(path, name); 56 | if (file.exists() && file.canRead() && file.length() > 1024) { 57 | return true; 58 | } 59 | 60 | file = new File(path, name + TEMP_POSTFIX); 61 | 62 | if (file.exists() && file.canRead() && file.length() > 102400) { 63 | return true; 64 | } 65 | } catch (Throwable e) { 66 | } 67 | return false; 68 | } 69 | 70 | public static String appendUrl(String url, String cacheKey) { 71 | StringBuilder appendQuery = new StringBuilder(100); 72 | appendQuery.append(PlayerEnvironment.VIDEO_CACHE_ID + "=" + cacheKey); 73 | return AndroidUtils.appendUri(url, appendQuery); 74 | } 75 | 76 | public static String appendUri(String uri, StringBuilder appendQuery) { 77 | String result = uri; 78 | try { 79 | Uri olduri = Uri.parse(uri); 80 | String newQuery = olduri.getEncodedQuery(); 81 | if (TextUtils.isEmpty(newQuery)) { 82 | newQuery = appendQuery.toString(); 83 | } else { 84 | newQuery = appendQuery + "&" + newQuery; 85 | } 86 | //todo ://?# 87 | Uri.Builder builder = new Uri.Builder(); 88 | builder.scheme(olduri.getScheme()).encodedAuthority(olduri.getEncodedAuthority()).encodedPath(olduri.getEncodedPath()).encodedQuery(newQuery).fragment(olduri.getEncodedFragment()); 89 | result = builder.build().toString(); 90 | } catch (Exception e) { 91 | 92 | } 93 | return result; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /videopreload/src/main/java/com/gibbon/videopreload/util/StorageUtils.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload.util; 2 | 3 | import android.content.Context; 4 | import android.os.Environment; 5 | 6 | import java.io.File; 7 | import java.io.Serializable; 8 | 9 | import static android.os.Environment.MEDIA_MOUNTED; 10 | 11 | /** 12 | * Provides application storage paths 13 | *

14 | * See https://github.com/nostra13/Android-Universal-Image-Loader 15 | * 16 | * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) 17 | * @since 1.0.0 18 | */ 19 | public final class StorageUtils implements Serializable { 20 | 21 | private static final String INDIVIDUAL_DIR_NAME = "video-cache"; 22 | 23 | 24 | /** 25 | * Returns individual application cache directory (for only video caching from Proxy). Cache directory will be 26 | * created on SD card ("/Android/data/[app_package_name]/cache/video-cache") if card is mounted . 27 | * Else - Android defines cache directory on device's file system. 28 | * 29 | * @param context Application context 30 | * @return Cache {@link File directory} 31 | */ 32 | public static File getIndividualCacheDirectory(Context context) { 33 | File cacheDir = getCacheDirectory(context, true); 34 | File file = new File(cacheDir, INDIVIDUAL_DIR_NAME); 35 | if (!file.exists()) { 36 | file.mkdirs(); 37 | } 38 | return file; 39 | } 40 | 41 | /** 42 | * Returns application cache directory. Cache directory will be created on SD card 43 | * ("/Android/data/[app_package_name]/cache") (if card is mounted and app has appropriate permission) or 44 | * on device's file system depending incoming parameters. 45 | * 46 | * @param context Application context 47 | * @param preferExternal Whether prefer external location for cache 48 | * @return Cache {@link File directory}.
49 | * NOTE: Can be null in some unpredictable cases (if SD card is unmounted and 50 | * {@link Context#getCacheDir() Context.getCacheDir()} returns null). 51 | */ 52 | private static File getCacheDirectory(Context context, boolean preferExternal) { 53 | File appCacheDir = null; 54 | String externalStorageState; 55 | try { 56 | externalStorageState = Environment.getExternalStorageState(); 57 | } catch (NullPointerException e) { // (sh)it happens 58 | externalStorageState = ""; 59 | } 60 | if (preferExternal && MEDIA_MOUNTED.equals(externalStorageState)) { 61 | appCacheDir = getExternalCacheDir(context); 62 | } 63 | if (appCacheDir == null) { 64 | appCacheDir = context.getCacheDir(); 65 | } 66 | if (appCacheDir == null) { 67 | String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/"; 68 | appCacheDir = new File(cacheDirPath); 69 | } 70 | return appCacheDir; 71 | } 72 | 73 | private static File getExternalCacheDir(Context context) { 74 | File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data"); 75 | File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache"); 76 | if (!appCacheDir.exists()) { 77 | if (!appCacheDir.mkdirs()) { 78 | return null; 79 | } 80 | } 81 | return appCacheDir; 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /videopreload/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | VideoPreload 3 | 4 | -------------------------------------------------------------------------------- /videopreload/src/test/java/com/gibbon/videopreload/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.gibbon.videopreload; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } --------------------------------------------------------------------------------