├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── fantasy │ │ └── androidwebview │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ ├── home.html │ │ ├── index.html │ │ └── upload.html │ ├── java │ │ └── com │ │ │ └── fantasy │ │ │ └── androidwebview │ │ │ ├── Constant.java │ │ │ ├── MyApplication.java │ │ │ ├── base │ │ │ ├── BaseActivity.java │ │ │ └── PermissionListener.java │ │ │ ├── main │ │ │ ├── ClearCacheActivity.java │ │ │ ├── MainActivity.java │ │ │ ├── UploadActivity.java │ │ │ ├── VideoActivity.java │ │ │ ├── WebActivity.java │ │ │ └── WelcomeActivity.java │ │ │ ├── scan │ │ │ └── ScanActivity.java │ │ │ └── utils │ │ │ ├── ConvertUtils.java │ │ │ ├── DirUtils.java │ │ │ ├── DownloadAsyncTask.java │ │ │ ├── IntentHelper.java │ │ │ ├── PreferencesUtils.java │ │ │ ├── TextHelper.java │ │ │ ├── WebViewUtils.java │ │ │ └── file │ │ │ ├── MyFileProvider.java │ │ │ └── OpenFileHelper.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ ├── cb_light_selector.xml │ │ ├── ic_launcher_background.xml │ │ └── pb_horizontal.xml │ │ ├── layout │ │ ├── activity_clear_cache.xml │ │ ├── activity_main.xml │ │ ├── activity_scan.xml │ │ ├── activity_web.xml │ │ ├── activity_welcome.xml │ │ ├── view_title_bar.xml │ │ └── view_warning_network.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── cb_light_off.png │ │ ├── cb_light_off0.png │ │ ├── cb_light_on.png │ │ ├── cb_light_on0.png │ │ ├── ic_arrow_right.png │ │ ├── ic_back.png │ │ ├── ic_close.png │ │ ├── ic_launcher.png │ │ ├── ic_launcher_round.png │ │ └── ic_warning_network.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 │ │ └── xml │ │ ├── my_file_provider_paths.xml │ │ └── network_security_config.xml │ └── test │ └── java │ └── com │ └── fantasy │ └── androidwebview │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.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 42 | 43 | # Keystore files 44 | # Uncomment the following lines if you do not want to check your keystore files in. 45 | #*.jks 46 | #*.keystore 47 | 48 | # External native build folder generated in Android Studio 2.2 and later 49 | .externalNativeBuild 50 | .cxx/ 51 | 52 | # Google Services (e.g. APIs or Firebase) 53 | # google-services.json 54 | 55 | # Freeline 56 | freeline.py 57 | freeline/ 58 | freeline_project_description.json 59 | 60 | # fastlane 61 | fastlane/report.xml 62 | fastlane/Preview.html 63 | fastlane/screenshots 64 | fastlane/test_output 65 | fastlane/readme.md 66 | 67 | # Version control 68 | vcs.xml 69 | 70 | # lint 71 | lint/intermediates/ 72 | lint/generated/ 73 | lint/outputs/ 74 | lint/tmp/ 75 | # lint/reports/ 76 | -------------------------------------------------------------------------------- /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 | # AndroidWebView 2 | 这是一个学习Android WebView的开源项目,涉及到WebView的基本用法、功能优化和常见问题的解决方案等等 3 | 4 | ## 博客文章 5 | 6 | * [Android WebView相关材料汇总](https://blog.csdn.net/Fantasy_Lin_/article/details/84989067) 7 | 8 | ## 项目功能 9 | 10 | * 自定义网页错误界面 11 | * 获取手机本地文件 12 | * 拍照 13 | * 定位 14 | * 同步Cookie 15 | * 设置请求头 16 | * 下载文件 17 | * 视频全屏 18 | * 清除缓存 19 | * 与H5交互(扫码、退出页面、监听手机返回键) 20 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | static def getTime() { 4 | return new Date().format("yyyyMMdd_HHmm") 5 | } 6 | 7 | android { 8 | compileSdkVersion 28 9 | defaultConfig { 10 | applicationId "com.fantasy.androidwebview" 11 | minSdkVersion 19 12 | targetSdkVersion 28 13 | versionCode 1 14 | versionName "1.0" 15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | applicationVariants.all { variant -> 24 | variant.outputs.all { 25 | outputFileName = "WV_V${variant.versionName}_${variant.versionCode}_${getTime()}.apk" 26 | } 27 | } 28 | } 29 | 30 | dependencies { 31 | implementation fileTree(dir: 'libs', include: ['*.jar']) 32 | implementation 'com.android.support:appcompat-v7:28.0.0' 33 | implementation 'com.android.support:cardview-v7:28.0.0' 34 | // 扫码,https://github.com/bingoogolapple/BGAQRCode-Android 35 | implementation 'cn.bingoogolapple:bga-qrcode-zxing:1.3.6' 36 | testImplementation 'junit:junit:4.12' 37 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 38 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 39 | } 40 | -------------------------------------------------------------------------------- /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/fantasy/androidwebview/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.fantasy.androidwebview", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 40 | 44 | 48 | 49 | 50 | 51 | 56 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /app/src/main/assets/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 首页 6 | 7 | 8 | 28 | 29 |
30 |

31 | 上传文件:

32 | 上传图片:

33 | 上传视频:

34 |

35 | 初始页,index.html 36 |

37 | 初始页,file:///android_asset/index.html 38 |

39 |

40 | 微信客户端(请点击这里下载) 41 |

42 | 打电话:18800000000 43 |

44 | 发短信:18800000000 45 |

46 | 发邮件:i_am_fantasy@163.com 47 |

48 |

49 |
退出
50 |
打开新的WebView来加载网页
(这里以“百度地图”为例)
51 |
调用手机浏览器加载网页
(这里以“百度地图”为例)
52 |
53 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /app/src/main/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 初始页 6 | 7 | 8 | 28 | 29 |
30 |
首页
31 |
退出
32 |
打开新的WebView来加载网页
(这里以“爱奇艺”为例)
33 |
调用手机浏览器加载网页
(这里以“爱奇艺”为例)
34 |
扫码
35 |
36 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /app/src/main/assets/upload.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 上传文件 6 | 7 | 8 | 28 | 29 |
30 |

31 | 上传文件:

32 | 上传图片:

33 | 上传视频:

34 |

35 |
36 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/Constant.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview; 2 | 3 | /** 4 | * 全局常量 5 | *
 6 |  *     author  : Fantasy
 7 |  *     version : 1.0, 2020-01-08
 8 |  *     since   : 1.0, 2020-01-07
 9 |  * 
10 | */ 11 | public class Constant { 12 | /** 13 | * 日志打印的标签 14 | */ 15 | public static final String TAG = "log"; 16 | /** 17 | * 活动之间传递数据的标识名 18 | */ 19 | public static final String EXTRA_DATA = "extraData"; 20 | /** 21 | * 存放已完全下载完的新版本安装包的路径 22 | */ 23 | public static final String PREF_DOWNLOAD_APK_PATH = "prefDownloadApkPath"; 24 | /** 25 | * 上一次申请相机权限的时间 26 | */ 27 | public static final String PREF_REQUEST_CAMERA_TIME = "prefRequestCameraTime"; 28 | } 29 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/MyApplication.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import com.fantasy.androidwebview.utils.DirUtils; 7 | import com.fantasy.androidwebview.utils.PreferencesUtils; 8 | 9 | /** 10 | * MyApplication 11 | *
12 |  *     author  : Fantasy
13 |  *     version : 1.0, 2020-01-07
14 |  *     since   : 1.0, 2020-01-07
15 |  * 
16 | */ 17 | public class MyApplication extends Application { 18 | private static Context sContext; 19 | 20 | @Override 21 | public void onCreate() { 22 | super.onCreate(); 23 | sContext = getApplicationContext(); 24 | DirUtils.init(this); 25 | PreferencesUtils.setPreferenceName(getPackageName() + ".sp"); 26 | } 27 | 28 | /** 29 | * 获取上下文 30 | * 31 | * @return 上下文 32 | */ 33 | public static Context getContext() { 34 | return sContext; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/base/BaseActivity.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.base; 2 | 3 | import android.app.ProgressDialog; 4 | import android.content.Context; 5 | import android.content.DialogInterface; 6 | import android.content.pm.PackageManager; 7 | import android.content.res.Configuration; 8 | import android.content.res.Resources; 9 | import android.os.Bundle; 10 | import android.support.annotation.NonNull; 11 | import android.support.annotation.Nullable; 12 | import android.support.v4.app.ActivityCompat; 13 | import android.support.v4.content.ContextCompat; 14 | import android.support.v7.app.AlertDialog; 15 | import android.support.v7.app.AppCompatActivity; 16 | import android.util.Log; 17 | import android.widget.Toast; 18 | 19 | import com.fantasy.androidwebview.Constant; 20 | import com.fantasy.androidwebview.R; 21 | 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | 25 | /** 26 | * 活动基础类 27 | *
 28 |  *     author  : Fantasy
 29 |  *     version : 1.0, 2020-04-10
 30 |  *     since   : 1.0, 2020-01-07
 31 |  * 
32 | */ 33 | public class BaseActivity extends AppCompatActivity { 34 | private ProgressDialog mLoadDialog; 35 | private ProgressDialog mDownloadDialog; 36 | private PermissionListener mPermissionListener; 37 | private static final int REQUEST_CODE_PERMISSION = 100; 38 | protected Context mContext; 39 | /** 40 | * 当前类名 41 | */ 42 | protected String mClassName; 43 | 44 | @Override 45 | protected void onCreate(@Nullable Bundle savedInstanceState) { 46 | super.onCreate(savedInstanceState); 47 | mContext = this; 48 | mClassName = getClass().getSimpleName(); 49 | Log.d(Constant.TAG, mClassName + " onCreate"); 50 | } 51 | 52 | @Override 53 | protected void onDestroy() { 54 | Log.d(Constant.TAG, mClassName + " onDestroy"); 55 | super.onDestroy(); 56 | } 57 | 58 | /** 59 | * 重写getResources()方法,让APP的字体不受系统设置字体大小影响 60 | */ 61 | @Override 62 | public Resources getResources() { 63 | Resources res = super.getResources(); 64 | Configuration config = new Configuration(); 65 | config.setToDefaults(); 66 | res.updateConfiguration(config, res.getDisplayMetrics()); 67 | return res; 68 | } 69 | 70 | /** 71 | * 显示加载对话框 72 | * 73 | * @param message 提示内容 74 | */ 75 | protected void showLoadDialog(String message) { 76 | if (mLoadDialog == null) { 77 | mLoadDialog = new ProgressDialog(this); 78 | mLoadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 79 | mLoadDialog.setCancelable(false); 80 | } 81 | mLoadDialog.setMessage(message); 82 | if (mLoadDialog != null && !mLoadDialog.isShowing()) { 83 | mLoadDialog.show(); 84 | } 85 | } 86 | 87 | /** 88 | * 关闭加载对话框 89 | */ 90 | protected void hideLoadDialog() { 91 | if (mLoadDialog != null && mLoadDialog.isShowing()) { 92 | mLoadDialog.dismiss(); 93 | } 94 | } 95 | 96 | /** 97 | * 显示下载对话框 98 | * 99 | * @param title 标题 100 | * @param progress 进度 101 | */ 102 | protected void showDownloadDialog(int title, int progress) { 103 | if (mDownloadDialog == null) { 104 | mDownloadDialog = new ProgressDialog(this); 105 | mDownloadDialog.setMax(100); 106 | mDownloadDialog.setTitle(title); 107 | mDownloadDialog.setCancelable(false); 108 | mDownloadDialog.setProgressPercentFormat(null); // 不显示百分比 109 | mDownloadDialog.setProgressStyle(android.app.ProgressDialog.STYLE_HORIZONTAL); 110 | } 111 | mDownloadDialog.setProgress(progress); 112 | if (mDownloadDialog != null && !mDownloadDialog.isShowing()) { 113 | mDownloadDialog.show(); 114 | } 115 | } 116 | 117 | /** 118 | * 显示下载对话框 119 | * 120 | * @param title 标题 121 | * @param progress 进度 122 | * @param listener “取消下载”的监听器 123 | */ 124 | protected void showDownloadDialog(int title, int progress, DialogInterface.OnClickListener listener) { 125 | if (mDownloadDialog == null) { 126 | mDownloadDialog = new ProgressDialog(this); 127 | mDownloadDialog.setMax(100); 128 | mDownloadDialog.setTitle(title); 129 | mDownloadDialog.setCancelable(false); 130 | mDownloadDialog.setProgressPercentFormat(null); // 不显示百分比 131 | mDownloadDialog.setProgressStyle(android.app.ProgressDialog.STYLE_HORIZONTAL); 132 | mDownloadDialog.setButton(DialogInterface.BUTTON_POSITIVE, 133 | getString(R.string.btn_cancel_download), listener); 134 | } 135 | mDownloadDialog.setProgress(progress); 136 | if (mDownloadDialog != null && !mDownloadDialog.isShowing()) { 137 | mDownloadDialog.show(); 138 | } 139 | } 140 | 141 | /** 142 | * 关闭下载对话框 143 | */ 144 | protected void hideDownloadDialog() { 145 | if (!this.isFinishing() && mDownloadDialog != null && mDownloadDialog.isShowing()) { 146 | mDownloadDialog.setProgress(0); 147 | mDownloadDialog.cancel(); 148 | } 149 | } 150 | 151 | /** 152 | * 短时间的Toast 153 | * 154 | * @param message 提示内容 155 | */ 156 | protected void showToast(String message) { 157 | Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); 158 | } 159 | 160 | /** 161 | * 短时间的Toast 162 | * 163 | * @param message 提示内容 164 | */ 165 | protected void showToast(int message) { 166 | Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); 167 | } 168 | 169 | /** 170 | * 长时间的Toast 171 | * 172 | * @param message 提示内容 173 | */ 174 | protected void showLongToast(String message) { 175 | Toast.makeText(this, message, Toast.LENGTH_LONG).show(); 176 | } 177 | 178 | /** 179 | * 长时间的Toast 180 | * 181 | * @param message 提示内容 182 | */ 183 | protected void showLongToast(int message) { 184 | Toast.makeText(this, message, Toast.LENGTH_LONG).show(); 185 | } 186 | 187 | /** 188 | * 提示对话框,带有“确定”按钮,而且setCancelable(false) 189 | * 190 | * @param message 提示内容 191 | * @param listener “确定”按钮的点击监听器 192 | */ 193 | protected void showConfirmDialog(String message, DialogInterface.OnClickListener listener) { 194 | AlertDialog dialog = new AlertDialog.Builder(this).setCancelable(false) 195 | .setMessage(message).setPositiveButton(R.string.btn_confirm, listener).create(); 196 | dialog.show(); 197 | } 198 | 199 | /** 200 | * 提示对话框,带有“确定”按钮,而且setCancelable(false) 201 | * 202 | * @param message 提示内容 203 | * @param listener “确定”按钮的点击监听器 204 | */ 205 | protected void showConfirmDialog(int message, DialogInterface.OnClickListener listener) { 206 | AlertDialog dialog = new AlertDialog.Builder(this).setCancelable(false) 207 | .setMessage(message).setPositiveButton(R.string.btn_confirm, listener).create(); 208 | dialog.show(); 209 | } 210 | 211 | /** 212 | * 提示对话框,带有“确定”按钮 213 | * 214 | * @param message 提示内容 215 | */ 216 | protected void showAlertDialog(String message) { 217 | AlertDialog dialog = new AlertDialog.Builder(this).setMessage(message) 218 | .setPositiveButton(R.string.btn_confirm, null).create(); 219 | dialog.setCanceledOnTouchOutside(false); 220 | dialog.show(); 221 | } 222 | 223 | /** 224 | * 提示对话框,带有“确定”按钮 225 | * 226 | * @param message 提示内容 227 | */ 228 | protected void showAlertDialog(int message) { 229 | AlertDialog dialog = new AlertDialog.Builder(this).setMessage(message) 230 | .setPositiveButton(R.string.btn_confirm, null).create(); 231 | dialog.setCanceledOnTouchOutside(false); 232 | dialog.show(); 233 | } 234 | 235 | /** 236 | * 提示对话框,带有“确定”按钮 237 | * 238 | * @param title 标题 239 | * @param message 提示内容 240 | */ 241 | protected void showAlertDialog(String title, String message) { 242 | AlertDialog dialog = new AlertDialog.Builder(this).setTitle(title).setMessage(message) 243 | .setPositiveButton(R.string.btn_confirm, null).create(); 244 | dialog.setCanceledOnTouchOutside(false); 245 | dialog.show(); 246 | } 247 | 248 | /** 249 | * 提示对话框,带有“确定”和“取消”两个按钮 250 | * 251 | * @param message 提示内容 252 | * @param listener “确定”按钮的点击监听器 253 | */ 254 | protected void showAlertDialog(String message, DialogInterface.OnClickListener listener) { 255 | AlertDialog dialog = new AlertDialog.Builder(this).setMessage(message) 256 | .setPositiveButton(R.string.btn_confirm, listener) 257 | .setNegativeButton(R.string.btn_cancel, null).create(); 258 | dialog.setCanceledOnTouchOutside(false); 259 | dialog.show(); 260 | } 261 | 262 | /** 263 | * 提示对话框,带有“确定”和“取消”两个按钮 264 | * 265 | * @param message 提示内容 266 | * @param listener “确定”按钮的点击监听器 267 | */ 268 | protected void showAlertDialog(int message, DialogInterface.OnClickListener listener) { 269 | AlertDialog dialog = new AlertDialog.Builder(this).setMessage(message) 270 | .setPositiveButton(R.string.btn_confirm, listener) 271 | .setNegativeButton(R.string.btn_cancel, null).create(); 272 | dialog.setCanceledOnTouchOutside(false); 273 | dialog.show(); 274 | } 275 | 276 | /** 277 | * 提示对话框,带有“确定”和“取消”两个按钮 278 | * 279 | * @param title 标题 280 | * @param message 提示内容 281 | * @param listener “确定”按钮的点击监听器 282 | */ 283 | protected void showAlertDialog(String title, String message, DialogInterface.OnClickListener listener) { 284 | AlertDialog dialog = new AlertDialog.Builder(this).setTitle(title).setMessage(message) 285 | .setPositiveButton(R.string.btn_confirm, listener) 286 | .setNegativeButton(R.string.btn_cancel, null).create(); 287 | dialog.setCanceledOnTouchOutside(false); 288 | dialog.show(); 289 | } 290 | 291 | /** 292 | * 提示对话框,带有“确定”和“取消”两个按钮,而且setCancelable(false) 293 | * 294 | * @param message 提示内容 295 | * @param positiveListener “确定”按钮的点击监听器 296 | * @param negativeListener “取消”按钮的点击监听器 297 | */ 298 | protected void showAlertDialog(String message, DialogInterface.OnClickListener positiveListener, 299 | DialogInterface.OnClickListener negativeListener) { 300 | AlertDialog dialog = new AlertDialog.Builder(this).setMessage(message) 301 | .setPositiveButton(R.string.btn_confirm, positiveListener) 302 | .setNegativeButton(R.string.btn_cancel, negativeListener).create(); 303 | dialog.setCancelable(false); 304 | dialog.show(); 305 | } 306 | 307 | /** 308 | * 提示对话框,带有“确定”和“取消”两个按钮,而且setCancelable(false) 309 | * 310 | * @param message 提示内容 311 | * @param positiveListener “确定”按钮的点击监听器 312 | * @param negativeListener “取消”按钮的点击监听器 313 | */ 314 | protected void showAlertDialog(int message, DialogInterface.OnClickListener positiveListener, 315 | DialogInterface.OnClickListener negativeListener) { 316 | AlertDialog dialog = new AlertDialog.Builder(this).setMessage(message) 317 | .setPositiveButton(R.string.btn_confirm, positiveListener) 318 | .setNegativeButton(R.string.btn_cancel, negativeListener).create(); 319 | dialog.setCancelable(false); 320 | dialog.show(); 321 | } 322 | 323 | /** 324 | * 申请运行时权限 325 | * 326 | * @param permissions 待申请的权限组 327 | * @param listener 回调监听器 328 | */ 329 | protected void requestPermissions(String[] permissions, PermissionListener listener) { 330 | mPermissionListener = listener; 331 | List deniedList = new ArrayList<>(); 332 | 333 | for (String permission : permissions) { 334 | if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) { 335 | deniedList.add(permission); 336 | } 337 | } 338 | 339 | if (deniedList.isEmpty()) { 340 | listener.onGranted(); 341 | } else { 342 | ActivityCompat.requestPermissions(this, 343 | deniedList.toArray(new String[deniedList.size()]), REQUEST_CODE_PERMISSION); 344 | } 345 | } 346 | 347 | @Override 348 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 349 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 350 | if (requestCode == REQUEST_CODE_PERMISSION) { 351 | if (grantResults.length > 0) { 352 | List deniedList = new ArrayList<>(); 353 | List grantedList = new ArrayList<>(); 354 | 355 | for (int i = 0; i < grantResults.length; i++) { 356 | int grantResult = grantResults[i]; 357 | if (grantResult != PackageManager.PERMISSION_GRANTED) { 358 | Log.d(Constant.TAG, mClassName + " denied : " + permissions[i]); 359 | deniedList.add(permissions[i]); 360 | } else { 361 | Log.d(Constant.TAG, mClassName + " granted : " + permissions[i]); 362 | grantedList.add(permissions[i]); 363 | } 364 | } 365 | 366 | if (deniedList.isEmpty()) { 367 | Log.d(Constant.TAG, mClassName + " requestPermissions onGranted all"); 368 | mPermissionListener.onGranted(); 369 | } else { 370 | Log.d(Constant.TAG, mClassName + " requestPermissions onDenied"); 371 | mPermissionListener.onDenied(deniedList); 372 | mPermissionListener.onGranted(grantedList); 373 | } 374 | } 375 | } 376 | } 377 | 378 | } 379 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/base/PermissionListener.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.base; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 申请运行时权限的回调监听器 7 | *
 8 |  *     author  : Fantasy
 9 |  *     version : 1.0, 2020-01-07
10 |  *     since   : 1.0, 2020-01-07
11 |  * 
12 | */ 13 | public interface PermissionListener { 14 | /** 15 | * 全部授权成功 16 | */ 17 | void onGranted(); 18 | 19 | /** 20 | * 部分授权成功 21 | * 22 | * @param grantedList 已授权成功的权限列表 23 | */ 24 | void onGranted(List grantedList); 25 | 26 | /** 27 | * 拒绝授权 28 | * 29 | * @param deniedList 未授权成功的权限列表 30 | */ 31 | void onDenied(List deniedList); 32 | } 33 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/main/ClearCacheActivity.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.main; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | import android.view.View; 7 | import android.widget.TextView; 8 | 9 | import com.fantasy.androidwebview.R; 10 | import com.fantasy.androidwebview.base.BaseActivity; 11 | import com.fantasy.androidwebview.utils.WebViewUtils; 12 | 13 | /** 14 | * 清除WebView缓存 15 | *
16 |  *     author  : Fantasy
17 |  *     version : 1.0, 2020-01-22
18 |  *     since   : 1.0, 2020-01-22
19 |  * 
20 | */ 21 | public class ClearCacheActivity extends BaseActivity implements View.OnClickListener { 22 | /** 23 | * 打开“清除WebView缓存”界面 24 | * 25 | * @param context 上下文 26 | */ 27 | public static void actionStart(Context context) { 28 | context.startActivity(new Intent(context, ClearCacheActivity.class)); 29 | } 30 | 31 | @Override 32 | protected void onCreate(Bundle savedInstanceState) { 33 | super.onCreate(savedInstanceState); 34 | setContentView(R.layout.activity_clear_cache); 35 | bindEvent(); 36 | } 37 | 38 | private void bindEvent() { 39 | ((TextView) findViewById(R.id.tv_title_bar_title)).setText(R.string.clear_cache_title); 40 | findViewById(R.id.iv_title_bar_back).setOnClickListener(this); 41 | findViewById(R.id.btn_clear_cache).setOnClickListener(this); 42 | findViewById(R.id.btn_clear_cache_web).setOnClickListener(this); 43 | } 44 | 45 | @Override 46 | public void onClick(View v) { 47 | switch (v.getId()) { 48 | case R.id.iv_title_bar_back: 49 | finish(); 50 | break; 51 | case R.id.btn_clear_cache: 52 | WebViewUtils.clearCache(mContext); 53 | break; 54 | case R.id.btn_clear_cache_web: 55 | WebActivity.actionStart(mContext, "https://www.baidu.com"); 56 | break; 57 | default: 58 | break; 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/main/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.main; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | import android.view.View; 7 | import android.widget.TextView; 8 | 9 | import com.fantasy.androidwebview.R; 10 | import com.fantasy.androidwebview.base.BaseActivity; 11 | 12 | /** 13 | * 主界面 14 | *
15 |  *     author  : Fantasy
16 |  *     version : 1.4, 2020-02-22
17 |  *     since   : 1.0, 2020-01-07
18 |  * 
19 | */ 20 | public class MainActivity extends BaseActivity implements View.OnClickListener { 21 | /** 22 | * 打开主界面 23 | * 24 | * @param context 上下文 25 | */ 26 | public static void actionStart(Context context) { 27 | context.startActivity(new Intent(context, MainActivity.class)); 28 | } 29 | 30 | @Override 31 | protected void onCreate(Bundle savedInstanceState) { 32 | super.onCreate(savedInstanceState); 33 | setContentView(R.layout.activity_main); 34 | bindEvent(); 35 | } 36 | 37 | private void bindEvent() { 38 | findViewById(R.id.iv_title_bar_back).setVisibility(View.GONE); 39 | ((TextView) findViewById(R.id.tv_title_bar_title)).setText(R.string.app_name); 40 | findViewById(R.id.cd_main_web_view).setOnClickListener(this); 41 | findViewById(R.id.cd_main_clear_cache).setOnClickListener(this); 42 | findViewById(R.id.cd_main_web_view_video).setOnClickListener(this); 43 | findViewById(R.id.cd_main_web_view_upload).setOnClickListener(this); 44 | } 45 | 46 | @Override 47 | public void onBackPressed() { 48 | Intent intent = new Intent(); 49 | intent.setAction("android.intent.action.MAIN"); 50 | intent.addCategory("android.intent.category.HOME"); 51 | startActivity(intent); 52 | } 53 | 54 | @Override 55 | public void onClick(View v) { 56 | switch (v.getId()) { 57 | case R.id.cd_main_web_view: 58 | WebActivity.actionStart(mContext, "file:///android_asset/index.html"); 59 | break; 60 | case R.id.cd_main_clear_cache: 61 | ClearCacheActivity.actionStart(mContext); 62 | break; 63 | case R.id.cd_main_web_view_video: 64 | VideoActivity.actionStart(mContext, "http://www.iqiyi.com"); 65 | break; 66 | case R.id.cd_main_web_view_upload: 67 | UploadActivity.actionStart(mContext, "file:///android_asset/upload.html"); 68 | break; 69 | default: 70 | break; 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/main/UploadActivity.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.main; 2 | 3 | import android.Manifest; 4 | import android.annotation.SuppressLint; 5 | import android.annotation.TargetApi; 6 | import android.content.Context; 7 | import android.content.DialogInterface; 8 | import android.content.Intent; 9 | import android.content.pm.PackageManager; 10 | import android.net.Uri; 11 | import android.os.Build; 12 | import android.os.Bundle; 13 | import android.provider.MediaStore; 14 | import android.support.v4.app.ActivityCompat; 15 | import android.support.v4.content.ContextCompat; 16 | import android.text.TextUtils; 17 | import android.util.Log; 18 | import android.view.KeyEvent; 19 | import android.view.View; 20 | import android.webkit.ValueCallback; 21 | import android.webkit.WebChromeClient; 22 | import android.webkit.WebSettings; 23 | import android.webkit.WebView; 24 | import android.webkit.WebViewClient; 25 | import android.widget.FrameLayout; 26 | import android.widget.ImageView; 27 | import android.widget.LinearLayout; 28 | import android.widget.TextView; 29 | 30 | import com.fantasy.androidwebview.Constant; 31 | import com.fantasy.androidwebview.R; 32 | import com.fantasy.androidwebview.base.BaseActivity; 33 | import com.fantasy.androidwebview.base.PermissionListener; 34 | import com.fantasy.androidwebview.utils.DirUtils; 35 | import com.fantasy.androidwebview.utils.PreferencesUtils; 36 | import com.fantasy.androidwebview.utils.WebViewUtils; 37 | 38 | import java.io.File; 39 | import java.text.SimpleDateFormat; 40 | import java.util.Date; 41 | import java.util.List; 42 | import java.util.Locale; 43 | 44 | /** 45 | * WebView拍照和上传文件 46 | *
 47 |  *     author  : Fantasy
 48 |  *     version : 1.0, 2020-02-22
 49 |  *     since   : 1.0, 2020-02-22
 50 |  * 
51 | */ 52 | public class UploadActivity extends BaseActivity implements View.OnClickListener { 53 | private LinearLayout mLlWeb; 54 | private ImageView mIvClose; 55 | private TextView mTvTitle; 56 | private FrameLayout mFlWeb; 57 | private WebView mWebView; 58 | 59 | private String mAppName; 60 | private String mAcceptType; 61 | private String mCameraPhotoPath; 62 | private ValueCallback mUploadMessage; 63 | private ValueCallback mUploadMessageAnother; 64 | private static final int REQUEST_CODE_FILE_CHOOSER = 0; 65 | private static final int REQUEST_CODE_FILE_CHOOSER_ANOTHER = 1; 66 | /** 67 | * 拍照上传的请求码 68 | */ 69 | private static final int REQUEST_CODE_PHOTO_UPLOAD = 3; 70 | 71 | /** 72 | * 启动WebActivity 73 | * 74 | * @param context 上下文 75 | * @param url 网址 76 | */ 77 | public static void actionStart(Context context, String url) { 78 | Intent intent = new Intent(context, UploadActivity.class); 79 | intent.putExtra("url", url); 80 | context.startActivity(intent); 81 | } 82 | 83 | @Override 84 | protected void onCreate(Bundle savedInstanceState) { 85 | super.onCreate(savedInstanceState); 86 | setContentView(R.layout.activity_web); 87 | bindEvent(); 88 | initWebView(); 89 | initData(); 90 | } 91 | 92 | @Override 93 | protected void onResume() { 94 | if (mWebView != null) { 95 | // 激活WebView为活跃状态,能正常执行网页的响应 96 | mWebView.onResume(); 97 | } 98 | super.onResume(); 99 | } 100 | 101 | @Override 102 | protected void onPause() { 103 | super.onPause(); 104 | if (mWebView != null) { 105 | // 当页面被失去焦点被切换到后台不可见状态,需要执行onPause 106 | // 通过onPause动作通知内核暂停所有的动作,比如DOM的解析、plugin的执行、JavaScript执行 107 | mWebView.onPause(); 108 | } 109 | } 110 | 111 | @Override 112 | protected void onDestroy() { 113 | if (mWebView != null) { 114 | mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); 115 | mFlWeb.removeView(mWebView); // 在退出时,移除WebView,可以防止其在后台消耗资源 116 | // clearCache()和destroy()这两个方法,要在移除WebView后调用,不然APP会崩溃 117 | mWebView.clearHistory(); 118 | //mWebView.clearCache(true); // 屏蔽的原因:加载网页会保存缓存,如果清掉缓存了,则每次打开网页会重新下载资源 119 | mWebView.destroy(); 120 | mWebView = null; 121 | } 122 | super.onDestroy(); 123 | } 124 | 125 | @Override 126 | public boolean onKeyDown(int keyCode, KeyEvent event) { 127 | if (keyCode == KeyEvent.KEYCODE_BACK) { 128 | goBack(); 129 | return true; 130 | } 131 | return super.onKeyDown(keyCode, event); 132 | } 133 | 134 | private void bindEvent() { 135 | mLlWeb = findViewById(R.id.ll_web); 136 | mIvClose = findViewById(R.id.iv_title_bar_close); 137 | mTvTitle = findViewById(R.id.tv_title_bar_title); 138 | mFlWeb = findViewById(R.id.fl_web); 139 | mWebView = findViewById(R.id.wv_web); 140 | 141 | mIvClose.setOnClickListener(this); 142 | findViewById(R.id.iv_title_bar_back).setOnClickListener(this); 143 | } 144 | 145 | private void initData() { 146 | mAppName = getString(R.string.app_name); 147 | mWebView.loadUrl(getIntent().getStringExtra("url")); 148 | } 149 | 150 | @Override 151 | public void onClick(View v) { 152 | switch (v.getId()) { 153 | case R.id.iv_title_bar_back: 154 | goBack(); 155 | break; 156 | case R.id.iv_title_bar_close: 157 | finish(); 158 | break; 159 | } 160 | } 161 | 162 | @SuppressLint("SetJavaScriptEnabled") 163 | private void initWebView() { 164 | WebSettings settings = mWebView.getSettings(); 165 | settings.setAppCacheEnabled(true); // 开启 Application Caches 功能 166 | settings.setDomStorageEnabled(true); // 开启 DOM storage API 功能 167 | settings.setAllowFileAccess(true); // 设置可以访问文件,默认启用 168 | settings.setJavaScriptEnabled(true); // 如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript 169 | settings.setJavaScriptCanOpenWindowsAutomatically(true); // 支持通过JS打开新窗口 170 | 171 | settings.setCacheMode(WebSettings.LOAD_DEFAULT); // 设置缓存模式 172 | // 缓存模式如下: 173 | // LOAD_CACHE_ONLY: 不使用网络,只读取本地缓存数据 174 | // LOAD_DEFAULT: (默认)根据cache-control决定是否从网络上取数据 175 | // LOAD_NO_CACHE: 不使用缓存,只从网络获取数据 176 | // LOAD_CACHE_ELSE_NETWORK,只要本地有,无论是否过期,或者no-cache,都使用缓存中的数据 177 | 178 | settings.setSavePassword(false); // 禁止自动保存密码 179 | settings.setSupportZoom(true); // 支持缩放 180 | settings.setBuiltInZoomControls(true); // 启动缩放机制 181 | settings.setDisplayZoomControls(false); // 隐藏原生缩放控件,即缩小放大两个按钮 182 | settings.setUseWideViewPort(true); // 将图片调整到适合WebView的大小 183 | settings.setLoadWithOverviewMode(true); // 缩放内容以适应屏幕大小 184 | 185 | // 设置请求头的User-Agent,前端可以通过这来判断页面是不是运行在自家的APP中(这里用 Fantasy 来作为自家的APP标识) 186 | settings.setUserAgentString(settings.getUserAgentString() + " Fantasy"); 187 | 188 | settings.setGeolocationEnabled(true); // 启用地理定位,默认为true 189 | String dir = getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 190 | settings.setGeolocationDatabasePath(dir); // 设置定位的数据库路径 191 | 192 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 193 | settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // 支持HTTP和HTTPS混合 194 | } 195 | 196 | WebViewUtils.removeJavascriptInterfaces(mWebView); 197 | 198 | mWebView.setWebViewClient(new WebViewClient() { 199 | @Override 200 | public void onPageFinished(WebView view, String url) { 201 | super.onPageFinished(view, url); 202 | // 页面加载结束 203 | mTvTitle.setText(view.getTitle()); // 获取网页的标题并设置在自定义的标题栏上面 204 | if (view.canGoBack()) { 205 | mIvClose.setVisibility(View.VISIBLE); 206 | } else { 207 | mIvClose.setVisibility(View.GONE); 208 | } 209 | } 210 | }); 211 | 212 | mWebView.setWebChromeClient(new WebChromeClient() { 213 | // 扩展浏览器上传文件 214 | // For Android < 3.0 215 | public void openFileChooser(ValueCallback uploadMsg) { 216 | mAcceptType = "*/*"; 217 | toOpenFileChooser(uploadMsg); 218 | } 219 | 220 | // For Android >= 3.0 221 | public void openFileChooser(ValueCallback uploadMsg, String acceptType) { 222 | if (TextUtils.isEmpty(acceptType)) { 223 | mAcceptType = "*/*"; 224 | } 225 | mAcceptType = acceptType; 226 | toOpenFileChooser(uploadMsg); 227 | } 228 | 229 | // For Android >= 4.1.1 230 | public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) { 231 | if (TextUtils.isEmpty(acceptType)) { 232 | mAcceptType = "*/*"; 233 | } 234 | mAcceptType = acceptType; 235 | toOpenFileChooser(uploadMsg); 236 | } 237 | 238 | // For Android >= 5.0 239 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 240 | @Override 241 | public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, 242 | FileChooserParams fileChooserParams) { 243 | String[] acceptTypes = fileChooserParams.getAcceptTypes(); 244 | if (acceptTypes.length > 0) { 245 | if (TextUtils.isEmpty(acceptTypes[0])) { 246 | mAcceptType = "*/*"; 247 | } else { 248 | mAcceptType = acceptTypes[0]; 249 | } 250 | } else { 251 | mAcceptType = "*/*"; 252 | } 253 | toOpenFileChooserAnother(filePathCallback); 254 | return true; 255 | } 256 | }); 257 | } 258 | 259 | /** 260 | * 返回 261 | */ 262 | private void goBack() { 263 | finish(); 264 | } 265 | 266 | /** 267 | * 申请相机权限 268 | */ 269 | private void toRequestCameraPermission() { 270 | String message = mAppName + getString(R.string.main_permission_photo_upload); 271 | 272 | showAlertDialog(message, new DialogInterface.OnClickListener() { 273 | @Override 274 | public void onClick(DialogInterface dialog, int which) { 275 | dialog.dismiss(); 276 | 277 | String[] permissions = new String[]{ 278 | Manifest.permission.CAMERA 279 | }; 280 | 281 | requestPermissions(permissions, new PermissionListener() { 282 | @Override 283 | public void onGranted() { 284 | toOpenFileChooserAnother(); 285 | } 286 | 287 | @Override 288 | public void onGranted(List grantedList) { 289 | } 290 | 291 | @Override 292 | public void onDenied(List deniedList) { 293 | if (ActivityCompat.shouldShowRequestPermissionRationale(UploadActivity.this, Manifest.permission.CAMERA)) { 294 | toRequestCameraPermission(); 295 | } else { 296 | showAlertDialog(String.format(getString(R.string.main_permission_photo_upload_1), mAppName), new DialogInterface.OnClickListener() { 297 | @Override 298 | public void onClick(DialogInterface dialog, int which) { 299 | dialog.dismiss(); 300 | Intent intent = new Intent(); 301 | intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); 302 | intent.addCategory("android.intent.category.DEFAULT"); 303 | intent.setData(Uri.parse("package:" + UploadActivity.this.getPackageName())); 304 | startActivityForResult(intent, REQUEST_CODE_PHOTO_UPLOAD); 305 | } 306 | }, new DialogInterface.OnClickListener() { 307 | @Override 308 | public void onClick(DialogInterface dialog, int which) { 309 | dialog.dismiss(); 310 | toOpenFileChooserAnother(); 311 | } 312 | }); 313 | } 314 | } 315 | }); 316 | } 317 | }, new DialogInterface.OnClickListener() { 318 | @Override 319 | public void onClick(DialogInterface dialog, int which) { 320 | dialog.dismiss(); 321 | toOpenFileChooserAnother(); 322 | } 323 | }); 324 | } 325 | 326 | /** 327 | * 打开文件选择器,适用于Android 5.0 以下 328 | * 329 | * @param uploadMsg 加载文件的信息 330 | */ 331 | private void toOpenFileChooser(ValueCallback uploadMsg) { 332 | mUploadMessage = uploadMsg; 333 | Intent i = new Intent(Intent.ACTION_GET_CONTENT); 334 | i.addCategory(Intent.CATEGORY_OPENABLE); 335 | i.setType(mAcceptType); 336 | startActivityForResult(Intent.createChooser(i, getString(R.string.choose_app)), REQUEST_CODE_FILE_CHOOSER); 337 | } 338 | 339 | /** 340 | * 打开文件选择器,适用于Android 5.0 及以上 341 | * 342 | * @param uploadMsg 加载文件的信息 343 | */ 344 | private void toOpenFileChooserAnother(ValueCallback uploadMsg) { 345 | mUploadMessageAnother = uploadMsg; 346 | if ((mAcceptType.equals("*/*") || mAcceptType.contains("image")) 347 | && ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) { 348 | long oldTime = PreferencesUtils.getLong(mContext, Constant.PREF_REQUEST_CAMERA_TIME); 349 | long newTime = System.currentTimeMillis(); 350 | 351 | if (oldTime == -1) { // 首次要提示申请权限 352 | PreferencesUtils.putLong(mContext, Constant.PREF_REQUEST_CAMERA_TIME, newTime); 353 | toRequestCameraPermission(); 354 | return; 355 | } else { 356 | if (newTime - oldTime >= 7 * 24 * 60 * 60 * 1000) { // 7天后再提示申请权限 357 | PreferencesUtils.putLong(mContext, Constant.PREF_REQUEST_CAMERA_TIME, newTime); 358 | toRequestCameraPermission(); 359 | return; 360 | } 361 | } 362 | } 363 | toOpenFileChooserAnother(); 364 | } 365 | 366 | /** 367 | * 打开文件选择器,适用于Android 5.0 及以上 368 | */ 369 | private void toOpenFileChooserAnother() { 370 | Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 371 | if ((mAcceptType.equals("*/*") || mAcceptType.contains("image")) 372 | && takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) { 373 | File photoFile = null; 374 | try { 375 | if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { 376 | String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()); 377 | String imageFileName = "PIC_" + timeStamp + "_"; 378 | File storageDir = new File(DirUtils.getPictures()); 379 | if (!storageDir.exists()) { 380 | storageDir.mkdirs(); 381 | } 382 | photoFile = File.createTempFile(imageFileName, ".jpg", storageDir); 383 | } 384 | } catch (Exception e) { 385 | Log.d(Constant.TAG, mClassName + " Unable to create Image File", e); 386 | } 387 | 388 | if (photoFile != null) { 389 | mCameraPhotoPath = photoFile.getAbsolutePath(); 390 | Log.d(Constant.TAG, "图片路径 : " + mCameraPhotoPath); 391 | takePictureIntent.putExtra("PhotoPath", "file:" + mCameraPhotoPath); 392 | takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); 393 | } else { 394 | takePictureIntent = null; 395 | } 396 | } else { 397 | takePictureIntent = null; 398 | } 399 | 400 | Intent[] intentArray; 401 | if (takePictureIntent != null) { 402 | intentArray = new Intent[]{takePictureIntent}; 403 | } else { 404 | intentArray = new Intent[0]; 405 | } 406 | 407 | Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); 408 | contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); 409 | contentSelectionIntent.setType(mAcceptType); 410 | 411 | Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); 412 | chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); 413 | chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_app)); 414 | chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); 415 | 416 | startActivityForResult(chooserIntent, REQUEST_CODE_FILE_CHOOSER_ANOTHER); 417 | } 418 | 419 | @Override 420 | protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 421 | switch (requestCode) { 422 | case REQUEST_CODE_FILE_CHOOSER: 423 | if (mUploadMessage == null) { 424 | return; 425 | } 426 | Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData(); 427 | mUploadMessage.onReceiveValue(result); 428 | mUploadMessage = null; 429 | break; 430 | case REQUEST_CODE_FILE_CHOOSER_ANOTHER: // Android 5.0 及以上 431 | if (mUploadMessageAnother == null) { 432 | return; 433 | } 434 | 435 | Uri[] results = null; 436 | if (resultCode == RESULT_OK) { 437 | if (intent != null) { 438 | results = new Uri[]{intent.getData()}; 439 | } else { 440 | if (mCameraPhotoPath != null) { 441 | results = new Uri[]{Uri.parse("file:" + mCameraPhotoPath)}; 442 | } 443 | } 444 | } else { 445 | if (!TextUtils.isEmpty(mCameraPhotoPath)) { 446 | File file = new File(mCameraPhotoPath); 447 | file.delete(); 448 | } 449 | } 450 | 451 | mUploadMessageAnother.onReceiveValue(results); 452 | mUploadMessageAnother = null; 453 | break; 454 | case REQUEST_CODE_PHOTO_UPLOAD: 455 | toOpenFileChooserAnother(); 456 | break; 457 | default: 458 | super.onActivityResult(requestCode, resultCode, intent); 459 | break; 460 | } 461 | } 462 | 463 | } 464 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/main/VideoActivity.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.main; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.pm.ActivityInfo; 7 | import android.os.Build; 8 | import android.os.Bundle; 9 | import android.os.Handler; 10 | import android.util.Log; 11 | import android.view.KeyEvent; 12 | import android.view.View; 13 | import android.view.WindowManager; 14 | import android.webkit.WebChromeClient; 15 | import android.webkit.WebSettings; 16 | import android.webkit.WebView; 17 | import android.webkit.WebViewClient; 18 | import android.widget.FrameLayout; 19 | import android.widget.ImageView; 20 | import android.widget.LinearLayout; 21 | import android.widget.TextView; 22 | 23 | import com.fantasy.androidwebview.Constant; 24 | import com.fantasy.androidwebview.R; 25 | import com.fantasy.androidwebview.base.BaseActivity; 26 | import com.fantasy.androidwebview.utils.IntentHelper; 27 | import com.fantasy.androidwebview.utils.WebViewUtils; 28 | 29 | /** 30 | * WebView播放视频并支持全屏 31 | *
 32 |  *     author  : Fantasy
 33 |  *     version : 1.0, 2020-02-13
 34 |  *     since   : 1.0, 2020-02-13
 35 |  * 
36 | */ 37 | public class VideoActivity extends BaseActivity implements View.OnClickListener { 38 | private LinearLayout mLlWeb; 39 | private ImageView mIvClose; 40 | private TextView mTvTitle; 41 | private FrameLayout mFlWeb; 42 | private WebView mWebView; 43 | private FrameLayout mFlVideoContainer; 44 | 45 | private boolean mIsShowVideo; 46 | 47 | /** 48 | * 启动WebActivity 49 | * 50 | * @param context 上下文 51 | * @param url 网址 52 | */ 53 | public static void actionStart(Context context, String url) { 54 | Intent intent = new Intent(context, VideoActivity.class); 55 | intent.putExtra("url", url); 56 | context.startActivity(intent); 57 | } 58 | 59 | @Override 60 | protected void onCreate(Bundle savedInstanceState) { 61 | super.onCreate(savedInstanceState); 62 | setContentView(R.layout.activity_web); 63 | bindEvent(); 64 | initWebView(); 65 | initData(); 66 | } 67 | 68 | @Override 69 | protected void onResume() { 70 | if (mWebView != null) { 71 | // 激活WebView为活跃状态,能正常执行网页的响应 72 | mWebView.onResume(); 73 | } 74 | super.onResume(); 75 | } 76 | 77 | @Override 78 | protected void onPause() { 79 | super.onPause(); 80 | if (mWebView != null) { 81 | // 当页面被失去焦点被切换到后台不可见状态,需要执行onPause 82 | // 通过onPause动作通知内核暂停所有的动作,比如DOM的解析、plugin的执行、JavaScript执行 83 | mWebView.onPause(); 84 | } 85 | } 86 | 87 | @Override 88 | protected void onDestroy() { 89 | if (mWebView != null) { 90 | mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); 91 | mFlWeb.removeView(mWebView); // 在退出时,移除WebView,可以防止其在后台消耗资源 92 | // clearCache()和destroy()这两个方法,要在移除WebView后调用,不然APP会崩溃 93 | mWebView.clearHistory(); 94 | //mWebView.clearCache(true); // 屏蔽的原因:加载网页会保存缓存,如果清掉缓存了,则每次打开网页会重新下载资源 95 | mWebView.destroy(); 96 | mWebView = null; 97 | } 98 | super.onDestroy(); 99 | } 100 | 101 | @Override 102 | public boolean onKeyDown(int keyCode, KeyEvent event) { 103 | if (keyCode == KeyEvent.KEYCODE_BACK) { 104 | goBack(); 105 | return true; 106 | } 107 | return super.onKeyDown(keyCode, event); 108 | } 109 | 110 | private void bindEvent() { 111 | mLlWeb = findViewById(R.id.ll_web); 112 | mIvClose = findViewById(R.id.iv_title_bar_close); 113 | mTvTitle = findViewById(R.id.tv_title_bar_title); 114 | mFlWeb = findViewById(R.id.fl_web); 115 | mWebView = findViewById(R.id.wv_web); 116 | mFlVideoContainer = findViewById(R.id.fl_web_video_container); 117 | 118 | mIvClose.setOnClickListener(this); 119 | findViewById(R.id.iv_title_bar_back).setOnClickListener(this); 120 | } 121 | 122 | private void initData() { 123 | mIsShowVideo = false; 124 | mWebView.loadUrl(getIntent().getStringExtra("url")); 125 | } 126 | 127 | @Override 128 | public void onClick(View v) { 129 | switch (v.getId()) { 130 | case R.id.iv_title_bar_back: 131 | goBack(); 132 | break; 133 | case R.id.iv_title_bar_close: 134 | finish(); 135 | break; 136 | } 137 | } 138 | 139 | @SuppressLint("SetJavaScriptEnabled") 140 | private void initWebView() { 141 | WebSettings settings = mWebView.getSettings(); 142 | settings.setAppCacheEnabled(true); // 开启 Application Caches 功能 143 | settings.setDomStorageEnabled(true); // 开启 DOM storage API 功能 144 | settings.setAllowFileAccess(true); // 设置可以访问文件,默认启用 145 | settings.setJavaScriptEnabled(true); // 如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript 146 | settings.setJavaScriptCanOpenWindowsAutomatically(true); // 支持通过JS打开新窗口 147 | 148 | settings.setCacheMode(WebSettings.LOAD_DEFAULT); // 设置缓存模式 149 | // 缓存模式如下: 150 | // LOAD_CACHE_ONLY: 不使用网络,只读取本地缓存数据 151 | // LOAD_DEFAULT: (默认)根据cache-control决定是否从网络上取数据 152 | // LOAD_NO_CACHE: 不使用缓存,只从网络获取数据 153 | // LOAD_CACHE_ELSE_NETWORK,只要本地有,无论是否过期,或者no-cache,都使用缓存中的数据 154 | 155 | settings.setSavePassword(false); // 禁止自动保存密码 156 | settings.setSupportZoom(true); // 支持缩放 157 | settings.setBuiltInZoomControls(true); // 启动缩放机制 158 | settings.setDisplayZoomControls(false); // 隐藏原生缩放控件,即缩小放大两个按钮 159 | settings.setUseWideViewPort(true); // 将图片调整到适合WebView的大小 160 | settings.setLoadWithOverviewMode(true); // 缩放内容以适应屏幕大小 161 | 162 | // 设置请求头的User-Agent,前端可以通过这来判断页面是不是运行在自家的APP中(这里用 Fantasy 来作为自家的APP标识) 163 | settings.setUserAgentString(settings.getUserAgentString() + " Fantasy"); 164 | 165 | settings.setGeolocationEnabled(true); // 启用地理定位,默认为true 166 | String dir = getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 167 | settings.setGeolocationDatabasePath(dir); // 设置定位的数据库路径 168 | 169 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 170 | settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // 支持HTTP和HTTPS混合 171 | } 172 | 173 | WebViewUtils.removeJavascriptInterfaces(mWebView); 174 | 175 | mWebView.setWebViewClient(new WebViewClient() { 176 | @Override 177 | public boolean shouldOverrideUrlLoading(WebView view, String url) { 178 | // 作用:打开网页时不调用系统浏览器,而是在本WebView中显示;在网页上的所有加载都经过这个方法 179 | Log.d(Constant.TAG, mClassName + " loading url : " + url); 180 | 181 | if (!url.startsWith("http") && !url.startsWith("file")) { 182 | try { 183 | IntentHelper.openBrowser(mContext, url); 184 | } catch (Exception e) { 185 | Log.d(Constant.TAG, mClassName + " WebViewClient Exception", e); 186 | if (url.startsWith("tel:")) { 187 | showToast(R.string.main_no_tel); 188 | } else if (url.startsWith("sms:")) { 189 | showToast(R.string.main_no_sms); 190 | } else if (url.startsWith("mailto:")) { 191 | showToast(R.string.main_no_mail); 192 | } else { 193 | showToast(R.string.load_failed); 194 | } 195 | } 196 | return true; 197 | } 198 | return super.shouldOverrideUrlLoading(view, url); 199 | } 200 | 201 | @Override 202 | public void onPageFinished(WebView view, String url) { 203 | super.onPageFinished(view, url); 204 | // 页面加载结束 205 | mTvTitle.setText(view.getTitle()); // 获取网页的标题并设置在自定义的标题栏上面 206 | if (view.canGoBack()) { 207 | mIvClose.setVisibility(View.VISIBLE); 208 | } else { 209 | mIvClose.setVisibility(View.GONE); 210 | } 211 | } 212 | }); 213 | 214 | mWebView.setWebChromeClient(new WebChromeClient() { 215 | @Override 216 | public void onShowCustomView(View view, CustomViewCallback callback) { 217 | // 进入视频全屏 218 | Log.d(Constant.TAG, mClassName + " onShowCustomView"); 219 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 横屏 220 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 221 | mLlWeb.setVisibility(View.GONE); 222 | mFlVideoContainer.setVisibility(View.VISIBLE); 223 | mFlVideoContainer.addView(view); 224 | mIsShowVideo = true; 225 | super.onShowCustomView(view, callback); 226 | } 227 | 228 | @Override 229 | public void onHideCustomView() { 230 | // 退出视频全屏 231 | Log.d(Constant.TAG, mClassName + " onHideCustomView"); 232 | //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 竖屏 233 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); // 默认值,系统根据方向感应自动选择屏幕方向 234 | getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 235 | mLlWeb.setVisibility(View.VISIBLE); 236 | mFlVideoContainer.setVisibility(View.GONE); 237 | mFlVideoContainer.removeAllViews(); 238 | new Handler().postDelayed(new Runnable() { 239 | @Override 240 | public void run() { 241 | // 点击手机返回键的话,会同时调用onKeyDown和onHideCustomView 242 | // 为了避免同时执行退出全屏和返回上一个网页这两个操作的情况出现,要延迟修改mIsShowVideo的值 243 | mIsShowVideo = false; 244 | } 245 | }, 800); 246 | super.onHideCustomView(); 247 | } 248 | }); 249 | } 250 | 251 | /** 252 | * 返回 253 | */ 254 | private void goBack() { 255 | if (mWebView.canGoBack()) { 256 | if (!mIsShowVideo) { 257 | mWebView.goBack(); 258 | } 259 | mIsShowVideo = false; 260 | } else { 261 | finish(); 262 | } 263 | } 264 | 265 | } 266 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/main/WelcomeActivity.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.main; 2 | 3 | import android.content.Intent; 4 | import android.graphics.Color; 5 | import android.os.Build; 6 | import android.os.Bundle; 7 | import android.os.Handler; 8 | import android.view.View; 9 | 10 | import com.fantasy.androidwebview.R; 11 | import com.fantasy.androidwebview.base.BaseActivity; 12 | 13 | /** 14 | * 欢迎页 15 | *
16 |  *     author  : Fantasy
17 |  *     version : 1.0, 2020-01-07
18 |  *     since   : 1.0, 2020-01-07
19 |  * 
20 | */ 21 | public class WelcomeActivity extends BaseActivity { 22 | 23 | @Override 24 | protected void onCreate(Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | 27 | // 解决Android应用Launcher重复启动的问题 28 | if (!isTaskRoot() && getIntent() != null) { 29 | String action = getIntent().getAction(); 30 | if (getIntent().hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) { 31 | finish(); 32 | return; 33 | } 34 | } 35 | 36 | setContentView(R.layout.activity_welcome); 37 | 38 | // 全屏,透明状态栏 39 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 40 | View decorView = getWindow().getDecorView(); 41 | int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; 42 | decorView.setSystemUiVisibility(option); 43 | getWindow().setStatusBarColor(Color.TRANSPARENT); 44 | } 45 | 46 | new Handler().postDelayed(new Runnable() { 47 | @Override 48 | public void run() { 49 | MainActivity.actionStart(WelcomeActivity.this); 50 | finish(); 51 | } 52 | }, 1500); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/scan/ScanActivity.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.scan; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.DialogInterface; 6 | import android.content.Intent; 7 | import android.graphics.Color; 8 | import android.os.Build; 9 | import android.os.Bundle; 10 | import android.os.Vibrator; 11 | import android.util.Log; 12 | import android.view.View; 13 | import android.widget.CheckBox; 14 | import android.widget.CompoundButton; 15 | import android.widget.ImageView; 16 | import android.widget.RelativeLayout; 17 | 18 | import com.fantasy.androidwebview.Constant; 19 | import com.fantasy.androidwebview.R; 20 | import com.fantasy.androidwebview.base.BaseActivity; 21 | import com.fantasy.androidwebview.utils.ConvertUtils; 22 | 23 | import cn.bingoogolapple.qrcode.core.QRCodeView; 24 | import cn.bingoogolapple.qrcode.zxing.ZXingView; 25 | 26 | /** 27 | * 扫码 28 | *
 29 |  *     author  : Fantasy
 30 |  *     version : 1.0, 2020-01-08
 31 |  *     since   : 1.0, 2020-01-08
 32 |  * 
33 | */ 34 | public class ScanActivity extends BaseActivity implements QRCodeView.Delegate { 35 | private ZXingView mZXingView; 36 | private ImageView mIvBack; 37 | /** 38 | * 是否返回结果 39 | */ 40 | private boolean mIsReturnResult; 41 | 42 | /** 43 | * 打开扫码,扫码结果在“扫码结果页”显示 44 | * 45 | * @param context 上下文 46 | */ 47 | public static void actionStart(Context context) { 48 | Intent intent = new Intent(context, ScanActivity.class); 49 | intent.putExtra("isReturnResult", false); 50 | context.startActivity(intent); 51 | } 52 | 53 | /** 54 | * 打开扫码,并且返回扫码结果 55 | * 56 | * @param activity 活动 57 | * @param requestCode 请求码 58 | */ 59 | public static void actionStart(Activity activity, int requestCode) { 60 | Intent intent = new Intent(activity, ScanActivity.class); 61 | intent.putExtra("isReturnResult", true); 62 | activity.startActivityForResult(intent, requestCode); 63 | } 64 | 65 | @Override 66 | protected void onCreate(Bundle savedInstanceState) { 67 | super.onCreate(savedInstanceState); 68 | setContentView(R.layout.activity_scan); 69 | 70 | // 透明状态栏 71 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 72 | View decorView = getWindow().getDecorView(); 73 | int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; 74 | decorView.setSystemUiVisibility(option); 75 | getWindow().setStatusBarColor(Color.TRANSPARENT); 76 | } 77 | 78 | bindEvent(); 79 | initData(); 80 | } 81 | 82 | @Override 83 | protected void onStart() { 84 | super.onStart(); 85 | mZXingView.startCamera(); 86 | mZXingView.startSpotAndShowRect(); 87 | } 88 | 89 | @Override 90 | protected void onStop() { 91 | mZXingView.stopCamera(); 92 | super.onStop(); 93 | } 94 | 95 | @Override 96 | protected void onDestroy() { 97 | mZXingView.onDestroy(); 98 | super.onDestroy(); 99 | } 100 | 101 | private void bindEvent() { 102 | mZXingView = findViewById(R.id.zxingview); 103 | mIvBack = findViewById(R.id.iv_scan_back); 104 | 105 | mIvBack.setOnClickListener(new View.OnClickListener() { 106 | @Override 107 | public void onClick(View v) { 108 | finish(); 109 | } 110 | }); 111 | 112 | ((CheckBox) findViewById(R.id.cb_scan_light)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 113 | @Override 114 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 115 | if (isChecked) { 116 | mZXingView.openFlashlight(); 117 | } else { 118 | mZXingView.closeFlashlight(); 119 | } 120 | } 121 | }); 122 | } 123 | 124 | private void initData() { 125 | mIsReturnResult = getIntent().getBooleanExtra("isReturnResult", false); 126 | 127 | mZXingView.setDelegate(this); 128 | //mZXingView.getScanBoxView().setOnlyDecodeScanBoxArea(true); // 仅识别扫描框中的码 129 | 130 | // 让返回按钮不被状态栏遮住 131 | int statusBarHeight = 0; 132 | int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); 133 | if (resourceId > 0) { 134 | statusBarHeight = getResources().getDimensionPixelSize(resourceId); 135 | } 136 | if (statusBarHeight <= 0) { 137 | statusBarHeight = 60; 138 | } 139 | RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mIvBack.getLayoutParams(); 140 | layoutParams.topMargin = statusBarHeight + ConvertUtils.dpToPx(15); 141 | mIvBack.setLayoutParams(layoutParams); 142 | } 143 | 144 | @Override 145 | public void onScanQRCodeSuccess(String result) { 146 | Log.d(Constant.TAG, mClassName + " result : " + result); 147 | 148 | Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 149 | if (vibrator != null) { 150 | vibrator.vibrate(200); 151 | } 152 | 153 | if (mIsReturnResult) { 154 | setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_DATA, result)); 155 | finish(); 156 | } 157 | } 158 | 159 | @Override 160 | public void onCameraAmbientBrightnessChanged(boolean isDark) { 161 | } 162 | 163 | @Override 164 | public void onScanQRCodeOpenCameraError() { 165 | showConfirmDialog(R.string.scan_error, new DialogInterface.OnClickListener() { 166 | @Override 167 | public void onClick(DialogInterface dialog, int which) { 168 | dialog.dismiss(); 169 | finish(); 170 | } 171 | }); 172 | } 173 | 174 | } -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/ConvertUtils.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.content.res.Resources; 6 | import android.graphics.Bitmap; 7 | import android.graphics.BitmapFactory; 8 | import android.graphics.Canvas; 9 | import android.graphics.Color; 10 | import android.graphics.PixelFormat; 11 | import android.graphics.drawable.BitmapDrawable; 12 | import android.graphics.drawable.Drawable; 13 | import android.support.annotation.IntDef; 14 | import android.view.View; 15 | 16 | import java.io.ByteArrayInputStream; 17 | import java.io.ByteArrayOutputStream; 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | import java.io.OutputStream; 21 | import java.io.UnsupportedEncodingException; 22 | import java.lang.annotation.Retention; 23 | import java.lang.annotation.RetentionPolicy; 24 | 25 | /** 26 | * 数据转换工具类 27 | *
 28 |  *     author  : Fantasy
 29 |  *     version : 1.0, 2020-01-08
 30 |  *     since   : 1.0, 2020-01-08
 31 |  * 
32 | */ 33 | public class ConvertUtils { 34 | public static final int BYTE = 1; 35 | public static final int KB = 1024; 36 | public static final int MB = 1048576; 37 | public static final int GB = 1073741824; 38 | 39 | public static final int MSEC = 1; 40 | public static final int SEC = 1000; 41 | public static final int MIN = 60000; 42 | public static final int HOUR = 3600000; 43 | public static final int DAY = 86400000; 44 | 45 | @IntDef({BYTE, KB, MB, GB}) 46 | @Retention(RetentionPolicy.SOURCE) 47 | @interface memoryUnit { 48 | } 49 | 50 | @IntDef({MSEC, SEC, MIN, HOUR, DAY}) 51 | @Retention(RetentionPolicy.SOURCE) 52 | @interface timeUnit { 53 | } 54 | 55 | private ConvertUtils() { 56 | throw new UnsupportedOperationException("u can't instantiate me..."); 57 | } 58 | 59 | private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 60 | 'A', 'B', 'C', 'D', 'E', 'F'}; 61 | 62 | /** 63 | * Bytes to bits. 64 | * 65 | * @param bytes The bytes. 66 | * @return bits 67 | */ 68 | public static String bytesToBits(byte[] bytes) { 69 | if (bytes == null || bytes.length == 0) return ""; 70 | StringBuilder sb = new StringBuilder(); 71 | for (byte aByte : bytes) { 72 | for (int j = 7; j >= 0; --j) { 73 | sb.append(((aByte >> j) & 0x01) == 0 ? '0' : '1'); 74 | } 75 | } 76 | return sb.toString(); 77 | } 78 | 79 | /** 80 | * Bits to bytes. 81 | * 82 | * @param bits The bits. 83 | * @return bytes 84 | */ 85 | public static byte[] bitsToBytes(String bits) { 86 | int lenMod = bits.length() % 8; 87 | int byteLen = bits.length() / 8; 88 | // add "0" until length to 8 times 89 | if (lenMod != 0) { 90 | for (int i = lenMod; i < 8; i++) { 91 | bits = "0" + bits; 92 | } 93 | byteLen++; 94 | } 95 | byte[] bytes = new byte[byteLen]; 96 | for (int i = 0; i < byteLen; ++i) { 97 | for (int j = 0; j < 8; ++j) { 98 | bytes[i] <<= 1; 99 | bytes[i] |= bits.charAt(i * 8 + j) - '0'; 100 | } 101 | } 102 | return bytes; 103 | } 104 | 105 | /** 106 | * Bytes to chars. 107 | * 108 | * @param bytes The bytes. 109 | * @return chars 110 | */ 111 | public static char[] bytesToChars(byte[] bytes) { 112 | if (bytes == null) return null; 113 | int len = bytes.length; 114 | if (len <= 0) return null; 115 | char[] chars = new char[len]; 116 | for (int i = 0; i < len; i++) { 117 | chars[i] = (char) (bytes[i] & 0xff); 118 | } 119 | return chars; 120 | } 121 | 122 | /** 123 | * Chars to bytes. 124 | * 125 | * @param chars The chars. 126 | * @return bytes 127 | */ 128 | public static byte[] charsToBytes(char[] chars) { 129 | if (chars == null || chars.length <= 0) return null; 130 | int len = chars.length; 131 | byte[] bytes = new byte[len]; 132 | for (int i = 0; i < len; i++) { 133 | bytes[i] = (byte) (chars[i]); 134 | } 135 | return bytes; 136 | } 137 | 138 | /** 139 | * Bytes to hex string. 140 | *

e.g. bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns "00A8"

141 | * 142 | * @param bytes The bytes. 143 | * @return hex string 144 | */ 145 | public static String bytesToHexString(byte[] bytes) { 146 | if (bytes == null) return ""; 147 | int len = bytes.length; 148 | if (len <= 0) return ""; 149 | char[] ret = new char[len << 1]; 150 | for (int i = 0, j = 0; i < len; i++) { 151 | ret[j++] = HEX_DIGITS[bytes[i] >> 4 & 0x0f]; 152 | ret[j++] = HEX_DIGITS[bytes[i] & 0x0f]; 153 | } 154 | return new String(ret); 155 | } 156 | 157 | /** 158 | * Hex string to bytes. 159 | *

e.g. hexString2Bytes("00A8") returns { 0, (byte) 0xA8 }

160 | * 161 | * @param hexString The hex string. 162 | * @return the bytes 163 | */ 164 | public static byte[] hexStringToBytes(String hexString) { 165 | if (isSpace(hexString)) return null; 166 | int len = hexString.length(); 167 | if (len % 2 != 0) { 168 | hexString = "0" + hexString; 169 | len = len + 1; 170 | } 171 | char[] hexBytes = hexString.toUpperCase().toCharArray(); 172 | byte[] ret = new byte[len >> 1]; 173 | for (int i = 0; i < len; i += 2) { 174 | ret[i >> 1] = (byte) (hexToDec(hexBytes[i]) << 4 | hexToDec(hexBytes[i + 1])); 175 | } 176 | return ret; 177 | } 178 | 179 | /** 180 | * Hex to dec. 181 | *

e.g. hex2Dec('F') returns 16

182 | * 183 | * @param hexChar The hex char. 184 | * @return the int 185 | */ 186 | private static int hexToDec(char hexChar) { 187 | if (hexChar >= '0' && hexChar <= '9') { 188 | return hexChar - '0'; 189 | } else if (hexChar >= 'A' && hexChar <= 'F') { 190 | return hexChar - 'A' + 10; 191 | } else { 192 | throw new IllegalArgumentException(); 193 | } 194 | } 195 | 196 | /** 197 | * Size of memory in unit to size of byte. 198 | * 199 | * @param memorySize Size of memory. 200 | * @param unit The unit of memory size. 201 | *
    202 | *
  • {@link #BYTE}
  • 203 | *
  • {@link #KB}
  • 204 | *
  • {@link #MB}
  • 205 | *
  • {@link #GB}
  • 206 | *
207 | * @return size of byte 208 | */ 209 | public static long memorySizeToByte(long memorySize, @memoryUnit int unit) { 210 | if (memorySize < 0) return -1; 211 | return memorySize * unit; 212 | } 213 | 214 | /** 215 | * Size of byte to size of memory in unit. 216 | * 217 | * @param byteSize Size of byte. 218 | * @param unit The unit of memory size. 219 | *
    220 | *
  • {@link #BYTE}
  • 221 | *
  • {@link #KB}
  • 222 | *
  • {@link #MB}
  • 223 | *
  • {@link #GB}
  • 224 | *
225 | * @return size of memory in unit 226 | */ 227 | public static double byteToMemorySize(long byteSize, @memoryUnit int unit) { 228 | if (byteSize < 0) return -1; 229 | return (double) byteSize / unit; 230 | } 231 | 232 | /** 233 | * Size of byte to fit size of memory. 234 | *

to three decimal places

235 | * 236 | * @param byteSize Size of byte. 237 | * @return fit size of memory 238 | */ 239 | @SuppressLint("DefaultLocale") 240 | public static String byteToFitMemorySize(long byteSize) { 241 | if (byteSize < 0) { 242 | return "shouldn't be less than zero!"; 243 | } else if (byteSize < KB) { 244 | return String.format("%.3fB", (double) byteSize); 245 | } else if (byteSize < MB) { 246 | return String.format("%.3fKB", (double) byteSize / KB); 247 | } else if (byteSize < GB) { 248 | return String.format("%.3fMB", (double) byteSize / MB); 249 | } else { 250 | return String.format("%.3fGB", (double) byteSize / GB); 251 | } 252 | } 253 | 254 | /** 255 | * Time span in unit to milliseconds. 256 | * 257 | * @param timeSpan The time span. 258 | * @param unit The unit of time span. 259 | *
    260 | *
  • {@link #MSEC}
  • 261 | *
  • {@link #SEC }
  • 262 | *
  • {@link #MIN }
  • 263 | *
  • {@link #HOUR}
  • 264 | *
  • {@link #DAY }
  • 265 | *
266 | * @return milliseconds 267 | */ 268 | public static long timeSpanToMillis(long timeSpan, @timeUnit int unit) { 269 | return timeSpan * unit; 270 | } 271 | 272 | /** 273 | * Milliseconds to time span in unit. 274 | * 275 | * @param millis The milliseconds. 276 | * @param unit The unit of time span. 277 | *
    278 | *
  • {@link #MSEC}
  • 279 | *
  • {@link #SEC }
  • 280 | *
  • {@link #MIN }
  • 281 | *
  • {@link #HOUR}
  • 282 | *
  • {@link #DAY }
  • 283 | *
284 | * @return time span in unit 285 | */ 286 | public static long millisToTimeSpan(long millis, @timeUnit int unit) { 287 | return millis / unit; 288 | } 289 | 290 | /** 291 | * Milliseconds to fit time span. 292 | * 293 | * @param millis The milliseconds. 294 | *

millis <= 0, return null

295 | * @param precision The precision of time span. 296 | *
    297 | *
  • precision = 0, return null
  • 298 | *
  • precision = 1, return 天
  • 299 | *
  • precision = 2, return 天, 小时
  • 300 | *
  • precision = 3, return 天, 小时, 分钟
  • 301 | *
  • precision = 4, return 天, 小时, 分钟, 秒
  • 302 | *
  • precision >= 5,return 天, 小时, 分钟, 秒, 毫秒
  • 303 | *
304 | * @return fit time span 305 | */ 306 | @SuppressLint("DefaultLocale") 307 | public static String millisToFitTimeSpan(long millis, int precision) { 308 | if (millis <= 0 || precision <= 0) return null; 309 | StringBuilder sb = new StringBuilder(); 310 | String[] units = {"天", "小时", "分钟", "秒", "毫秒"}; 311 | int[] unitLen = {86400000, 3600000, 60000, 1000, 1}; 312 | precision = Math.min(precision, 5); 313 | for (int i = 0; i < precision; i++) { 314 | if (millis >= unitLen[i]) { 315 | long mode = millis / unitLen[i]; 316 | millis -= mode * unitLen[i]; 317 | sb.append(mode).append(units[i]); 318 | } 319 | } 320 | return sb.toString(); 321 | } 322 | 323 | /** 324 | * Input stream to output stream. 325 | * 326 | * @param is The input stream. 327 | * @return output stream 328 | */ 329 | public static ByteArrayOutputStream inputToOutputStream(InputStream is) { 330 | if (is == null) return null; 331 | try { 332 | ByteArrayOutputStream os = new ByteArrayOutputStream(); 333 | byte[] b = new byte[KB]; 334 | int len; 335 | while ((len = is.read(b, 0, KB)) != -1) { 336 | os.write(b, 0, len); 337 | } 338 | return os; 339 | } catch (IOException e) { 340 | e.printStackTrace(); 341 | return null; 342 | } finally { 343 | try { 344 | is.close(); 345 | } catch (IOException e) { 346 | e.printStackTrace(); 347 | } 348 | } 349 | } 350 | 351 | /** 352 | * Output stream to input stream. 353 | * 354 | * @param out The output stream. 355 | * @return input stream 356 | */ 357 | public ByteArrayInputStream outputToInputStream(OutputStream out) { 358 | if (out == null) return null; 359 | return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray()); 360 | } 361 | 362 | /** 363 | * Input stream to bytes. 364 | * 365 | * @param is The input stream. 366 | * @return bytes 367 | */ 368 | public static byte[] inputStreamToBytes(InputStream is) { 369 | if (is == null) return null; 370 | return inputToOutputStream(is).toByteArray(); 371 | } 372 | 373 | /** 374 | * Bytes to input stream. 375 | * 376 | * @param bytes The bytes. 377 | * @return input stream 378 | */ 379 | public static InputStream bytesToInputStream(byte[] bytes) { 380 | if (bytes == null || bytes.length <= 0) return null; 381 | return new ByteArrayInputStream(bytes); 382 | } 383 | 384 | /** 385 | * Output stream to bytes. 386 | * 387 | * @param out The output stream. 388 | * @return bytes 389 | */ 390 | public static byte[] outputStreamToBytes(OutputStream out) { 391 | if (out == null) return null; 392 | return ((ByteArrayOutputStream) out).toByteArray(); 393 | } 394 | 395 | /** 396 | * Bytes to output stream. 397 | * 398 | * @param bytes The bytes. 399 | * @return output stream 400 | */ 401 | public static OutputStream bytesToOutputStream(byte[] bytes) { 402 | if (bytes == null || bytes.length <= 0) return null; 403 | ByteArrayOutputStream os = null; 404 | try { 405 | os = new ByteArrayOutputStream(); 406 | os.write(bytes); 407 | return os; 408 | } catch (IOException e) { 409 | e.printStackTrace(); 410 | return null; 411 | } finally { 412 | try { 413 | if (os != null) { 414 | os.close(); 415 | } 416 | } catch (IOException e) { 417 | e.printStackTrace(); 418 | } 419 | } 420 | } 421 | 422 | /** 423 | * Input stream to string. 424 | * 425 | * @param is The input stream. 426 | * @param charsetName The name of charset. 427 | * @return string 428 | */ 429 | public static String inputStreamToString(InputStream is, String charsetName) { 430 | if (is == null || isSpace(charsetName)) return ""; 431 | try { 432 | ByteArrayOutputStream baos = inputToOutputStream(is); 433 | if (baos == null) return ""; 434 | return baos.toString(charsetName); 435 | } catch (UnsupportedEncodingException e) { 436 | e.printStackTrace(); 437 | return ""; 438 | } 439 | } 440 | 441 | /** 442 | * String to input stream. 443 | * 444 | * @param string The string. 445 | * @param charsetName The name of charset. 446 | * @return input stream 447 | */ 448 | public static InputStream stringToInputStream(String string, String charsetName) { 449 | if (string == null || isSpace(charsetName)) return null; 450 | try { 451 | return new ByteArrayInputStream(string.getBytes(charsetName)); 452 | } catch (UnsupportedEncodingException e) { 453 | e.printStackTrace(); 454 | return null; 455 | } 456 | } 457 | 458 | /** 459 | * Output stream to string. 460 | * 461 | * @param out The output stream. 462 | * @param charsetName The name of charset. 463 | * @return string 464 | */ 465 | public static String outputStreamToString(OutputStream out, String charsetName) { 466 | if (out == null || isSpace(charsetName)) return ""; 467 | try { 468 | return new String(outputStreamToBytes(out), charsetName); 469 | } catch (UnsupportedEncodingException e) { 470 | e.printStackTrace(); 471 | return ""; 472 | } 473 | } 474 | 475 | /** 476 | * String to output stream. 477 | * 478 | * @param string The string. 479 | * @param charsetName The name of charset. 480 | * @return output stream 481 | */ 482 | public static OutputStream stringToOutputStream(String string, String charsetName) { 483 | if (string == null || isSpace(charsetName)) return null; 484 | try { 485 | return bytesToOutputStream(string.getBytes(charsetName)); 486 | } catch (UnsupportedEncodingException e) { 487 | e.printStackTrace(); 488 | return null; 489 | } 490 | } 491 | 492 | /** 493 | * Bitmap to bytes. 494 | * 495 | * @param bitmap The bitmap. 496 | * @param format The format of bitmap. 497 | * @return bytes 498 | */ 499 | public static byte[] bitmapToBytes(Bitmap bitmap, Bitmap.CompressFormat format) { 500 | if (bitmap == null) return null; 501 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 502 | bitmap.compress(format, 100, baos); 503 | return baos.toByteArray(); 504 | } 505 | 506 | /** 507 | * Bytes to bitmap. 508 | * 509 | * @param bytes The bytes. 510 | * @return bitmap 511 | */ 512 | public static Bitmap bytesToBitmap(byte[] bytes) { 513 | return (bytes == null || bytes.length == 0) 514 | ? null 515 | : BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 516 | } 517 | 518 | /** 519 | * Drawable to bitmap. 520 | * 521 | * @param drawable The drawable. 522 | * @return bitmap 523 | */ 524 | public static Bitmap drawableToBitmap(Drawable drawable) { 525 | if (drawable instanceof BitmapDrawable) { 526 | BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; 527 | if (bitmapDrawable.getBitmap() != null) { 528 | return bitmapDrawable.getBitmap(); 529 | } 530 | } 531 | Bitmap bitmap; 532 | if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { 533 | bitmap = Bitmap.createBitmap(1, 1, 534 | drawable.getOpacity() != PixelFormat.OPAQUE 535 | ? Bitmap.Config.ARGB_8888 536 | : Bitmap.Config.RGB_565); 537 | } else { 538 | bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), 539 | drawable.getIntrinsicHeight(), 540 | drawable.getOpacity() != PixelFormat.OPAQUE 541 | ? Bitmap.Config.ARGB_8888 542 | : Bitmap.Config.RGB_565); 543 | } 544 | Canvas canvas = new Canvas(bitmap); 545 | drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 546 | drawable.draw(canvas); 547 | return bitmap; 548 | } 549 | 550 | /** 551 | * Bitmap to drawable. 552 | * 553 | * @param context The context. 554 | * @param bitmap The bitmap. 555 | * @return drawable 556 | */ 557 | public static Drawable bitmapToDrawable(Context context, Bitmap bitmap) { 558 | return bitmap == null ? null : new BitmapDrawable(context.getResources(), bitmap); 559 | } 560 | 561 | /** 562 | * Drawable to bytes. 563 | * 564 | * @param drawable The drawable. 565 | * @param format The format of bitmap. 566 | * @return bytes 567 | */ 568 | public static byte[] drawableToBytes(Drawable drawable, Bitmap.CompressFormat format) { 569 | return drawable == null ? null : bitmapToBytes(drawableToBitmap(drawable), format); 570 | } 571 | 572 | /** 573 | * Bytes to drawable. 574 | * 575 | * @param context The context. 576 | * @param bytes The bytes. 577 | * @return drawable 578 | */ 579 | public static Drawable bytesToDrawable(Context context, byte[] bytes) { 580 | return bytes == null ? null : bitmapToDrawable(context, bytesToBitmap(bytes)); 581 | } 582 | 583 | /** 584 | * View to bitmap. 585 | * 586 | * @param view The view. 587 | * @return bitmap 588 | */ 589 | public static Bitmap viewToBitmap(View view) { 590 | if (view == null) return null; 591 | Bitmap ret = 592 | Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); 593 | Canvas canvas = new Canvas(ret); 594 | Drawable bgDrawable = view.getBackground(); 595 | if (bgDrawable != null) { 596 | bgDrawable.draw(canvas); 597 | } else { 598 | canvas.drawColor(Color.WHITE); 599 | } 600 | view.draw(canvas); 601 | return ret; 602 | } 603 | 604 | /** 605 | * Value of dp to value of px. 606 | * 607 | * @param dpValue The value of dp. 608 | * @return value of px 609 | */ 610 | public static int dpToPx(float dpValue) { 611 | float scale = Resources.getSystem().getDisplayMetrics().density; 612 | return (int) (dpValue * scale + 0.5f); 613 | } 614 | 615 | /** 616 | * Value of px to value of dp. 617 | * 618 | * @param pxValue The value of px. 619 | * @return value of dp 620 | */ 621 | public static int pxToDp(float pxValue) { 622 | float scale = Resources.getSystem().getDisplayMetrics().density; 623 | return (int) (pxValue / scale + 0.5f); 624 | } 625 | 626 | /** 627 | * Value of sp to value of px. 628 | * 629 | * @param spValue The value of sp. 630 | * @return value of px 631 | */ 632 | public static int spToPx(float spValue) { 633 | float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity; 634 | return (int) (spValue * fontScale + 0.5f); 635 | } 636 | 637 | /** 638 | * Value of px to value of sp. 639 | * 640 | * @param pxValue The value of px. 641 | * @return value of sp 642 | */ 643 | public static int pxToSp(float pxValue) { 644 | float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity; 645 | return (int) (pxValue / fontScale + 0.5f); 646 | } 647 | 648 | private static boolean isSpace(String s) { 649 | if (s == null) return true; 650 | for (int i = 0, len = s.length(); i < len; ++i) { 651 | if (!Character.isWhitespace(s.charAt(i))) { 652 | return false; 653 | } 654 | } 655 | return true; 656 | } 657 | 658 | } 659 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/DirUtils.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils; 2 | 3 | import android.content.Context; 4 | 5 | import java.io.File; 6 | 7 | /** 8 | * APP文件目录的工具类,用于存放安装包、下载文件、图片等等 9 | *
 10 |  *     author  : Fantasy
 11 |  *     version : 1.0, 2020-01-07
 12 |  *     since   : 1.0, 2020-01-07
 13 |  * 
14 | */ 15 | public class DirUtils { 16 | /** 17 | * 根目录 18 | */ 19 | private static String mPathRoot; 20 | /** 21 | * 缓存目录 22 | */ 23 | private static String mPathCache; 24 | /** 25 | * 下载文件目录 26 | */ 27 | private static String mPathDownload; 28 | /** 29 | * 日志目录 30 | */ 31 | private static String mPathLogs; 32 | /** 33 | * 图片目录 34 | */ 35 | private static String mPathPictures; 36 | /** 37 | * 更新文件目录 38 | */ 39 | private static String mPathUpdate; 40 | 41 | /** 42 | * 初始化文件目录 43 | * 44 | * @param context 上下文 45 | */ 46 | public static void init(Context context) { 47 | File fileRoot = context.getExternalFilesDir(""); 48 | File fileCache = context.getExternalFilesDir("cache"); 49 | File fileDownload = context.getExternalFilesDir("download"); 50 | File fileLogs = context.getExternalFilesDir("logs"); 51 | File filePictures = context.getExternalFilesDir("pictures"); 52 | File fileUpdate = context.getExternalFilesDir("update"); 53 | 54 | if (fileRoot != null) { 55 | mPathRoot = fileRoot.getPath(); 56 | } 57 | if (fileCache != null) { 58 | mPathCache = fileCache.getPath(); 59 | } 60 | if (fileDownload != null) { 61 | mPathDownload = fileDownload.getPath(); 62 | } 63 | if (fileLogs != null) { 64 | mPathLogs = fileLogs.getPath(); 65 | } 66 | if (filePictures != null) { 67 | mPathPictures = filePictures.getPath(); 68 | } 69 | if (fileUpdate != null) { 70 | mPathUpdate = fileUpdate.getPath(); 71 | } 72 | } 73 | 74 | /** 75 | * 获取根目录 76 | * 77 | * @return /storage/emulated/0/Android/data/package name/files 78 | */ 79 | public static String getRoot() { 80 | return mPathRoot; 81 | } 82 | 83 | /** 84 | * 获取缓存目录 85 | * 86 | * @return /storage/emulated/0/Android/data/package name/files/cache 87 | */ 88 | public static String getCache() { 89 | return mPathCache; 90 | } 91 | 92 | /** 93 | * 获取下载文件目录 94 | * 95 | * @return /storage/emulated/0/Android/data/package name/files/download 96 | */ 97 | public static String getDownload() { 98 | return mPathDownload; 99 | } 100 | 101 | /** 102 | * 获取日志目录 103 | * 104 | * @return /storage/emulated/0/Android/data/package name/files/logs 105 | */ 106 | public static String getLogs() { 107 | return mPathLogs; 108 | } 109 | 110 | /** 111 | * 获取图片目录 112 | * 113 | * @return /storage/emulated/0/Android/data/package name/files/pictures 114 | */ 115 | public static String getPictures() { 116 | return mPathPictures; 117 | } 118 | 119 | /** 120 | * 获取更新文件目录 121 | * 122 | * @return /storage/emulated/0/Android/data/package name/files/update 123 | */ 124 | public static String getUpdate() { 125 | return mPathUpdate; 126 | } 127 | 128 | } 129 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/DownloadAsyncTask.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.Context; 5 | import android.os.AsyncTask; 6 | import android.text.TextUtils; 7 | import android.util.Log; 8 | 9 | import com.fantasy.androidwebview.Constant; 10 | 11 | import java.io.File; 12 | import java.io.FileNotFoundException; 13 | import java.io.FileOutputStream; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | import java.net.HttpURLConnection; 17 | import java.net.MalformedURLException; 18 | import java.net.SocketTimeoutException; 19 | import java.net.URL; 20 | import java.net.URLDecoder; 21 | 22 | /** 23 | * 下载工具类 24 | *
 25 |  *     author  : Fantasy
 26 |  *     version : 1.0, 2020-01-07
 27 |  *     since   : 1.0, 2020-01-07
 28 |  * 
29 | */ 30 | public class DownloadAsyncTask extends AsyncTask { 31 | /** 32 | * 下载成功 33 | */ 34 | private static final int SUCCESS = 0; 35 | /** 36 | * 网络连接异常 37 | */ 38 | private static final int ERROR_NETWORK = 1; 39 | /** 40 | * 网络连接超时 41 | */ 42 | private static final int ERROR_TIME_OUT = 2; 43 | /** 44 | * 服务响应失败 45 | */ 46 | private static final int ERROR_RESPONSE = 3; 47 | /** 48 | * 文件处理异常 49 | */ 50 | private static final int ERROR_IO = 4; 51 | /** 52 | * 存储文件失败 53 | */ 54 | private static final int ERROR_FILE_NOT_FOUND = 5; 55 | /** 56 | * 存储空间不足 57 | */ 58 | private static final int ERROR_SPACE = 6; 59 | /** 60 | * 无效的下载地址 61 | */ 62 | private static final int ERROR_URL = 7; 63 | /** 64 | * 下载的文件不存在 65 | */ 66 | private static final int ERROR_SOURCE = 8; 67 | 68 | private Context mContext = null; 69 | /** 70 | * 回调监听器 71 | */ 72 | private CallbackListener mListener = null; 73 | /** 74 | * 下载的文件大小 75 | */ 76 | private long mFileSize = 0; 77 | /** 78 | * 已下载成功的文件的绝对路径 79 | */ 80 | private String mFilePath = ""; 81 | /** 82 | * 是否取消下载 83 | */ 84 | private boolean sIsCancel = false; 85 | 86 | private DownloadAsyncTask(Context context, CallbackListener listener) { 87 | super(); 88 | mContext = context; 89 | mListener = listener; 90 | } 91 | 92 | @Override 93 | protected void onPreExecute() { 94 | mListener.onProgress(0); // 进度条初始化 95 | Log.d(Constant.TAG, "DownloadAsyncTask onPreExecute"); 96 | } 97 | 98 | @Override 99 | protected Integer doInBackground(String... params) { 100 | Log.d(Constant.TAG, "DownloadAsyncTask doInBackground"); 101 | HttpURLConnection connection = null; 102 | int code; 103 | InputStream is = null; 104 | FileOutputStream fos = null; 105 | 106 | try { 107 | String downloadUrl = params[0]; 108 | String path = params[1]; 109 | String fileName = params[2]; 110 | 111 | Log.d(Constant.TAG, "DownloadAsyncTask url : " + downloadUrl); 112 | 113 | connection = (HttpURLConnection) new URL(downloadUrl).openConnection(); 114 | connection.setRequestMethod("GET"); 115 | connection.setConnectTimeout(8 * 1000); 116 | connection.setReadTimeout(8 * 1000); 117 | // 要取得长度则,要求HTTP请求不要gzip压缩,具体设置如下,要不然出现length=-1的情况 118 | connection.setRequestProperty("Accept-Encoding", "identity"); 119 | connection.setRequestProperty("Connection", "Keep-Alive"); 120 | connection.connect(); 121 | code = connection.getResponseCode(); 122 | 123 | Log.d(Constant.TAG, "DownloadAsyncTask code : " + code); 124 | 125 | if (code == 200) { 126 | if (TextUtils.isEmpty(fileName)) { // 未设置文件名,则动态获取 127 | // 通过Content-Disposition获取文件名,这点跟服务器有关,需要灵活变通 128 | fileName = connection.getHeaderField("Content-Disposition"); 129 | if (TextUtils.isEmpty(fileName)) { 130 | // 通过截取URL来获取文件名 131 | fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1); 132 | } else { 133 | fileName = URLDecoder.decode(fileName.substring( 134 | fileName.indexOf("filename=") + 9), "UTF-8"); 135 | // 有些文件名会被包含在""里面,所以要去掉,不然无法读取文件后缀 136 | fileName = fileName.replaceAll("\"", ""); 137 | } 138 | } 139 | Log.d(Constant.TAG, "DownloadAsyncTask fileName : " + fileName); 140 | 141 | mFileSize = connection.getContentLength(); 142 | Log.d(Constant.TAG, "DownloadAsyncTask fileSize : " + mFileSize); 143 | if (isMemoryEnough(mFileSize)) { 144 | return ERROR_SPACE; 145 | } 146 | if (mFileSize <= 0) { 147 | return ERROR_SOURCE; 148 | } 149 | 150 | mFilePath = path + File.separator + fileName; 151 | Log.d(Constant.TAG, "DownloadAsyncTask filePath : " + mFilePath); 152 | 153 | File file = new File(mFilePath); 154 | File parent = file.getParentFile(); 155 | if (!parent.exists()) { 156 | parent.mkdirs(); 157 | } 158 | if (file.exists()) { // 删除已存在的文件 159 | file.delete(); 160 | } 161 | 162 | fos = new FileOutputStream(file); 163 | 164 | is = connection.getInputStream(); 165 | byte[] bytes = new byte[1024]; 166 | int temp = -1; 167 | int alreadyDownloadSize = 0; // 已经下载的大小 168 | 169 | while (true) { 170 | if (sIsCancel) { 171 | return null; 172 | } 173 | 174 | temp = is.read(bytes); 175 | fos.write(bytes, 0, temp); 176 | alreadyDownloadSize = alreadyDownloadSize + temp; 177 | publishProgress(alreadyDownloadSize); 178 | if (alreadyDownloadSize >= mFileSize) { 179 | return SUCCESS; 180 | } 181 | } 182 | } else { 183 | return ERROR_RESPONSE; 184 | } 185 | } catch (MalformedURLException e) { 186 | Log.d(Constant.TAG, "DownloadAsyncTask MalformedURLException", e); 187 | return ERROR_URL; 188 | } catch (SocketTimeoutException e) { 189 | Log.d(Constant.TAG, "DownloadAsyncTask SocketTimeoutException", e); 190 | return ERROR_TIME_OUT; 191 | } catch (ArrayIndexOutOfBoundsException e) { 192 | Log.d(Constant.TAG, "DownloadAsyncTask ArrayIndexOutOfBoundsException", e); 193 | return ERROR_IO; 194 | } catch (FileNotFoundException e) { 195 | Log.d(Constant.TAG, "DownloadAsyncTask FileNotFoundException", e); 196 | return ERROR_FILE_NOT_FOUND; 197 | } catch (Exception e) { 198 | Log.d(Constant.TAG, "DownloadAsyncTask Exception", e); 199 | return ERROR_NETWORK; 200 | } finally { 201 | try { 202 | if (is != null) { 203 | is.close(); 204 | } 205 | if (fos != null) { 206 | fos.close(); 207 | } 208 | } catch (IOException e) { 209 | Log.d(Constant.TAG, "DownloadAsyncTask IOException", e); 210 | } 211 | if (connection != null) { 212 | connection.disconnect(); 213 | } 214 | } 215 | } 216 | 217 | @Override 218 | protected void onProgressUpdate(Integer... values) { 219 | if (!sIsCancel) { 220 | double temp = (double) values[0] / mFileSize; 221 | int progress = (int) (temp * 100); 222 | mListener.onProgress(progress); 223 | } 224 | } 225 | 226 | @Override 227 | protected void onCancelled(Integer integer) { 228 | super.onCancelled(integer); 229 | Log.d(Constant.TAG, "DownloadAsyncTask onCancelled"); 230 | } 231 | 232 | @Override 233 | protected void onPostExecute(Integer integer) { 234 | Log.d(Constant.TAG, "DownloadAsyncTask onPostExecute"); 235 | switch (integer) { 236 | case SUCCESS: 237 | mListener.onSuccess(mFilePath); 238 | Log.d(Constant.TAG, "DownloadAsyncTask SUCCESS"); 239 | break; 240 | case ERROR_NETWORK: 241 | mListener.onError("网络连接异常,请稍后重试。"); 242 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_NETWORK"); 243 | break; 244 | case ERROR_TIME_OUT: 245 | mListener.onError("网络连接超时,请稍后重试。"); 246 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_TIME_OUT"); 247 | break; 248 | case ERROR_RESPONSE: 249 | mListener.onError("服务响应失败,请稍后重试。"); 250 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_RESPONSE"); 251 | break; 252 | case ERROR_IO: 253 | mListener.onError("文件处理异常,请稍后重试。"); 254 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_IO"); 255 | break; 256 | case ERROR_FILE_NOT_FOUND: 257 | mListener.onError("存储文件失败,请允许应用读写手机储存。"); 258 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_FILE_NOT_FOUND"); 259 | break; 260 | case ERROR_SPACE: 261 | mListener.onError("存储空间不足。"); 262 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_SPACE"); 263 | break; 264 | case ERROR_URL: 265 | mListener.onError("无效的下载地址。"); 266 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_URL"); 267 | break; 268 | case ERROR_SOURCE: 269 | mListener.onError("下载的文件不存在。"); 270 | Log.d(Constant.TAG, "DownloadAsyncTask ERROR_SOURCE"); 271 | break; 272 | default: 273 | break; 274 | } 275 | } 276 | 277 | /** 278 | * 执行下载任务 279 | * 280 | * @param context 上下文 281 | * @param url 下载地址 282 | * @param path 下载的文件所要存放的文件夹路径,以文件夹的名称结尾,例如:/storage/sdcard0/Download 283 | * @param fileName 下载的文件的名称,包含后缀,例如:demo.doc 284 | * @param listener 回调监听器 285 | * @return DownloadAsyncTask的实例 286 | */ 287 | public static DownloadAsyncTask execute(Context context, String url, String path, String fileName, 288 | CallbackListener listener) { 289 | DownloadAsyncTask asyncTask = new DownloadAsyncTask(context, listener); 290 | asyncTask.execute(url, path, fileName); 291 | return asyncTask; 292 | } 293 | 294 | /** 295 | * 执行下载任务,文件名动态获取 296 | * 297 | * @param context 上下文 298 | * @param url 下载地址 299 | * @param path 下载的文件所要存放的文件夹路径,以文件夹的名称结尾,例如:/storage/sdcard0/Download 300 | * @param listener 回调监听器 301 | * @return DownloadAsyncTask的实例 302 | */ 303 | public static DownloadAsyncTask execute(Context context, String url, String path, CallbackListener listener) { 304 | DownloadAsyncTask asyncTask = new DownloadAsyncTask(context, listener); 305 | asyncTask.execute(url, path, null); 306 | return asyncTask; 307 | } 308 | 309 | /** 310 | * 取消下载 311 | */ 312 | public void cancel() { 313 | sIsCancel = true; 314 | cancel(true); 315 | } 316 | 317 | /** 318 | * 判断内存是否充足 319 | * 320 | * @param fileSize 文件大小 321 | * @return 充足就返回true,反之返回false 322 | */ 323 | private boolean isMemoryEnough(long fileSize) { 324 | ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); 325 | ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); 326 | am.getMemoryInfo(mi); 327 | return fileSize >= mi.availMem; 328 | } 329 | 330 | /** 331 | * 回调监听器 332 | */ 333 | public interface CallbackListener { 334 | /** 335 | * 更新进度 336 | * 337 | * @param progress 进度值 338 | */ 339 | void onProgress(int progress); 340 | 341 | /** 342 | * 下载完成 343 | * 344 | * @param filePath 已下载的文件的绝对路径 345 | */ 346 | void onSuccess(String filePath); 347 | 348 | /** 349 | * 下载失败 350 | * 351 | * @param message 错误信息 352 | */ 353 | void onError(String message); 354 | } 355 | 356 | } 357 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/IntentHelper.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.net.Uri; 6 | import android.provider.Settings; 7 | 8 | /** 9 | * Intent帮助类 10 | *
11 |  *     author  : Fantasy
12 |  *     version : 1.0, 2020-01-07
13 |  *     since   : 1.0, 2020-01-07
14 |  * 
15 | */ 16 | public class IntentHelper { 17 | 18 | /** 19 | * 打开系统设置 20 | * 21 | * @param context 上下文 22 | */ 23 | public static void openSettings(Context context) { 24 | context.startActivity(new Intent(Settings.ACTION_SETTINGS)); 25 | } 26 | 27 | /** 28 | * 调用系统默认浏览器加载网页 29 | * 30 | * @param context 上下文 31 | * @param url 网址 32 | */ 33 | public static void openBrowser(Context context, String url) { 34 | context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); 35 | } 36 | 37 | /** 38 | * 调用拨号界面,并自动填写电话号码 39 | * 40 | * @param context 上下文 41 | * @param phone 电话号码,格式为123456 42 | */ 43 | public static void openDial(Context context, String phone) { 44 | context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone))); 45 | } 46 | 47 | /** 48 | * 调用系统发短信 49 | * 50 | * @param context 上下文 51 | * @param phone 电话号码 52 | * @param message 内容 53 | */ 54 | public static void sendSMS(Context context, String phone, String message) { 55 | Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone)); 56 | intent.putExtra("sms_body", message); 57 | context.startActivity(intent); 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/PreferencesUtils.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | /** 7 | * SharedPreferences工具类 8 | *
  9 |  *     author  : Fantasy
 10 |  *     version : 1.0, 2020-01-07
 11 |  *     since   : 1.0, 2020-01-07
 12 |  * 
13 | */ 14 | public class PreferencesUtils { 15 | private static String sPreferenceName = "preference_name"; 16 | 17 | public static void setPreferenceName(String name) { 18 | sPreferenceName = name; 19 | } 20 | 21 | public static boolean remove(Context context, String key) { 22 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 23 | SharedPreferences.Editor editor = settings.edit(); 24 | editor.remove(key); 25 | return editor.commit(); 26 | } 27 | 28 | public static void putString(Context context, String key, String value) { 29 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 30 | SharedPreferences.Editor editor = settings.edit(); 31 | editor.putString(key, value); 32 | editor.apply(); 33 | } 34 | 35 | public static boolean commitString(Context context, String key, String value) { 36 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 37 | SharedPreferences.Editor editor = settings.edit(); 38 | editor.putString(key, value); 39 | return editor.commit(); 40 | } 41 | 42 | public static String getString(Context context, String key) { 43 | return getString(context, key, null); 44 | } 45 | 46 | public static String getString(Context context, String key, String defaultValue) { 47 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 48 | return settings.getString(key, defaultValue); 49 | } 50 | 51 | public static void putInt(Context context, String key, int value) { 52 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 53 | SharedPreferences.Editor editor = settings.edit(); 54 | editor.putInt(key, value); 55 | editor.apply(); 56 | } 57 | 58 | public static boolean commitInt(Context context, String key, int value) { 59 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 60 | SharedPreferences.Editor editor = settings.edit(); 61 | editor.putInt(key, value); 62 | return editor.commit(); 63 | } 64 | 65 | public static int getInt(Context context, String key) { 66 | return getInt(context, key, -1); 67 | } 68 | 69 | public static int getInt(Context context, String key, int defaultValue) { 70 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 71 | return settings.getInt(key, defaultValue); 72 | } 73 | 74 | public static void putLong(Context context, String key, long value) { 75 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 76 | SharedPreferences.Editor editor = settings.edit(); 77 | editor.putLong(key, value); 78 | editor.apply(); 79 | } 80 | 81 | public static boolean commitLong(Context context, String key, long value) { 82 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 83 | SharedPreferences.Editor editor = settings.edit(); 84 | editor.putLong(key, value); 85 | return editor.commit(); 86 | } 87 | 88 | public static long getLong(Context context, String key) { 89 | return getLong(context, key, -1); 90 | } 91 | 92 | public static long getLong(Context context, String key, long defaultValue) { 93 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 94 | return settings.getLong(key, defaultValue); 95 | } 96 | 97 | public static void putFloat(Context context, String key, float value) { 98 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 99 | SharedPreferences.Editor editor = settings.edit(); 100 | editor.putFloat(key, value); 101 | editor.apply(); 102 | } 103 | 104 | public static boolean commitFloat(Context context, String key, float value) { 105 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 106 | SharedPreferences.Editor editor = settings.edit(); 107 | editor.putFloat(key, value); 108 | return editor.commit(); 109 | } 110 | 111 | public static float getFloat(Context context, String key) { 112 | return getFloat(context, key, -1); 113 | } 114 | 115 | public static float getFloat(Context context, String key, float defaultValue) { 116 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 117 | return settings.getFloat(key, defaultValue); 118 | } 119 | 120 | public static void putBoolean(Context context, String key, boolean value) { 121 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 122 | SharedPreferences.Editor editor = settings.edit(); 123 | editor.putBoolean(key, value); 124 | editor.apply(); 125 | } 126 | 127 | public static boolean commitBoolean(Context context, String key, boolean value) { 128 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 129 | SharedPreferences.Editor editor = settings.edit(); 130 | editor.putBoolean(key, value); 131 | return editor.commit(); 132 | } 133 | 134 | public static boolean getBoolean(Context context, String key) { 135 | return getBoolean(context, key, false); 136 | } 137 | 138 | public static boolean getBoolean(Context context, String key, boolean defaultValue) { 139 | SharedPreferences settings = context.getSharedPreferences(sPreferenceName, Context.MODE_PRIVATE); 140 | return settings.getBoolean(key, defaultValue); 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/TextHelper.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils; 2 | 3 | import java.util.regex.Pattern; 4 | 5 | /** 6 | * 文本帮助类
7 | *
 8 |  *     author  : Fantasy
 9 |  *     version : 1.0, 2020-04-30
10 |  *     since   : 1.0, 2020-04-30
11 |  * 
12 | */ 13 | public class TextHelper { 14 | 15 | /** 16 | * 判断身份证号码是否正确 17 | * 18 | * @param number 身份证号码 19 | * @return 如果正确的话,则返回true,否则返回false 20 | */ 21 | public static boolean isIdentificationNumber(String number) { 22 | String regex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)"; 23 | return Pattern.matches(regex, number); 24 | } 25 | 26 | /** 27 | * 判断手机号码的格式是否正确 28 | * 29 | * @param phone 手机号码 30 | * @return 如果正确的话,则返回true,否则返回false 31 | */ 32 | public static boolean isPhone(String phone) { 33 | String regex = "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$"; 34 | return Pattern.matches(regex, phone); 35 | } 36 | 37 | /** 38 | * 判断电话号码的格式是否正确 39 | * 40 | * @param tel 电话号码 41 | * @return 如果正确的话,则返回true,否则返回false 42 | */ 43 | public static boolean isTel(String tel) { 44 | String regex = "(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|" 45 | + "(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)"; 46 | return Pattern.matches(regex, tel); 47 | } 48 | 49 | /** 50 | * 处理传给JS函数的参数值。因为如果参数值带'、\n等特殊字符,JS会报错 51 | * 52 | * @param params 参数值 53 | * @return 已经处理过参数值 54 | */ 55 | public static String handleJSFunctionParams(String params) { 56 | return params.replace("'", "\\'") 57 | .replace("\"", "\\\"") 58 | .replace("\n", "\\n"); 59 | } 60 | 61 | } -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/WebViewUtils.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | import android.util.Log; 6 | import android.webkit.CookieManager; 7 | import android.webkit.CookieSyncManager; 8 | import android.webkit.WebView; 9 | 10 | import com.fantasy.androidwebview.Constant; 11 | 12 | import java.io.File; 13 | import java.util.Map; 14 | 15 | /** 16 | * WebView工具类 17 | *
 18 |  *     author  : Fantasy
 19 |  *     version : 1.0, 2020-01-07
 20 |  *     since   : 1.0, 2020-01-07
 21 |  * 
22 | */ 23 | public class WebViewUtils { 24 | private static final String TAG = "WebViewUtils"; 25 | 26 | /** 27 | * 移除有风险的WebView系统隐藏接口 28 | * 29 | * @param webView WebView实例 30 | */ 31 | public static void removeJavascriptInterfaces(WebView webView) { 32 | try { 33 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB 34 | && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { 35 | webView.removeJavascriptInterface("searchBoxJavaBridge_"); 36 | webView.removeJavascriptInterface("accessibility"); 37 | webView.removeJavascriptInterface("accessibilityTraversal"); 38 | } 39 | } catch (Exception e) { 40 | Log.d(Constant.TAG, TAG + " removeJavascriptInterfaces exception", e); 41 | } 42 | } 43 | 44 | /** 45 | * 同步Cookie 46 | * 47 | * @param context 上下文 48 | * @param url 链接 49 | * @param map Cookie键值对 50 | */ 51 | public static void syncCookie(Context context, String url, Map map) { 52 | try { 53 | // domain可以设置也可以不设置,非必需 54 | //String domain = url.replace("http://", "").replace("https://", ""); 55 | //if (domain.contains("/")) { 56 | // domain = domain.substring(0, domain.indexOf('/')); 57 | //} 58 | 59 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 60 | CookieSyncManager.createInstance(context); 61 | } 62 | CookieManager cookieManager = CookieManager.getInstance(); 63 | cookieManager.setAcceptCookie(true); 64 | // cookieManager.removeSessionCookie(); // 移除所有会话Cookie 65 | for (Map.Entry entry : map.entrySet()) { 66 | cookieManager.setCookie(url, entry.getKey() + "=" + entry.getValue()); 67 | //cookieManager.setCookie(url, "domain=" + domain); 68 | //cookieManager.setCookie(url, "path=" + "/"); 69 | } 70 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 71 | CookieSyncManager.getInstance().sync(); 72 | } else { 73 | cookieManager.flush(); 74 | } 75 | } catch (Exception e) { 76 | Log.d(Constant.TAG, TAG + " syncCookie exception", e); 77 | } 78 | } 79 | 80 | /** 81 | * 清除缓存 82 | * 83 | * @param context 上下文 84 | */ 85 | public static void clearCache(Context context) { 86 | try { 87 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 清除cookie 88 | CookieManager.getInstance().removeAllCookies(null); 89 | } else { 90 | CookieSyncManager.createInstance(context); 91 | CookieManager.getInstance().removeAllCookie(); 92 | CookieSyncManager.getInstance().sync(); 93 | } 94 | 95 | new WebView(context).clearCache(true); 96 | 97 | File cacheFile = new File(context.getCacheDir().getParent() + "/app_webview"); 98 | clearCacheFolder(cacheFile, System.currentTimeMillis()); 99 | } catch (Exception e) { 100 | Log.d(Constant.TAG, TAG + " clearCache exception", e); 101 | } 102 | } 103 | 104 | private static int clearCacheFolder(File dir, long time) { 105 | int deletedFiles = 0; 106 | if (dir != null && dir.isDirectory()) { 107 | try { 108 | for (File child : dir.listFiles()) { 109 | if (child.isDirectory()) { 110 | deletedFiles += clearCacheFolder(child, time); 111 | } 112 | if (child.lastModified() < time) { 113 | if (child.delete()) { 114 | deletedFiles++; 115 | } 116 | } 117 | } 118 | } catch (Exception e) { 119 | Log.d(Constant.TAG, TAG + " clearCacheFolder Exception", e); 120 | } 121 | } 122 | return deletedFiles; 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/file/MyFileProvider.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils.file; 2 | 3 | import android.support.v4.content.FileProvider; 4 | 5 | /** 6 | * 给自己的APP使用的FileProvider,这样可以避免与第三方库产生冲突 7 | *
 8 |  *     author  : Fantasy
 9 |  *     version : 1.0, 2020-01-08
10 |  *     since   : 1.0, 2020-01-08
11 |  * 
12 | */ 13 | public class MyFileProvider extends FileProvider { 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/com/fantasy/androidwebview/utils/file/OpenFileHelper.java: -------------------------------------------------------------------------------- 1 | package com.fantasy.androidwebview.utils.file; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.net.Uri; 6 | import android.os.Build; 7 | import android.support.v4.content.FileProvider; 8 | 9 | import java.io.File; 10 | import java.util.Locale; 11 | 12 | /** 13 | * 打开文件帮助类 14 | *
 15 |  *     author  : Fantasy
 16 |  *     version : 1.0, 2020-01-08
 17 |  *     since   : 1.0, 2020-01-08
 18 |  * 
19 | */ 20 | public class OpenFileHelper { 21 | 22 | /** 23 | * 获取打开文件的intent 24 | * 25 | * @param filePath 文件的路径 26 | * @return intent 27 | */ 28 | public static Intent getIntent(Context context, String filePath) { 29 | File file = new File(filePath); 30 | if (!file.exists()) { 31 | return null; 32 | } 33 | 34 | // 取得扩展名 35 | String fileName = file.getName(); 36 | String end = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); 37 | end = end.toLowerCase(Locale.ENGLISH); 38 | 39 | // 依扩展名的类型决定MimeType 40 | switch (end) { 41 | case "apk": 42 | return getApkFileIntent(context, filePath); 43 | case "ppt": 44 | return getPptFileIntent(context, filePath); 45 | case "pptx": 46 | return getPptxFileIntent(context, filePath); 47 | case "xls": 48 | return getExcelFileIntent(context, filePath); 49 | case "xlsx": 50 | return getXlsxFileIntent(context, filePath); 51 | case "doc": 52 | return getWordFileIntent(context, filePath); 53 | case "docx": 54 | return getDocxFileIntent(context, filePath); 55 | case "pdf": 56 | return getPdfFileIntent(context, filePath); 57 | case "chm": 58 | return getChmFileIntent(context, filePath); 59 | case "txt": 60 | return getTextFileIntent(context, filePath, true); 61 | case "html": 62 | return getHtmlFileIntent(context, filePath); 63 | case "m4a": 64 | case "mp3": 65 | case "mid": 66 | case "xmf": 67 | case "ogg": 68 | case "wav": 69 | return getAudioFileIntent(context, filePath); 70 | case "jpg": 71 | case "gif": 72 | case "png": 73 | case "jpeg": 74 | case "bmp": 75 | return getImageFileIntent(context, filePath); 76 | case "3gp": 77 | case "rmvb": 78 | case "mkv": 79 | case "mp4": 80 | return getVideoFileIntent(context, filePath); 81 | default: 82 | return getAllIntent(context, filePath); 83 | } 84 | } 85 | 86 | /** 87 | * 获取一个用于打开文件的intent 88 | * 89 | * @param context 上下文 90 | * @param filePath 文件的路径 91 | */ 92 | public static Intent getAllIntent(Context context, String filePath) { 93 | Intent intent = new Intent(); 94 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 95 | // 添加这一句表示对目标应用临时授权该Uri所代表的文件 96 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 97 | } 98 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 99 | intent.setAction(Intent.ACTION_VIEW); 100 | Uri uri = getUriForFile(context, new File(filePath)); 101 | intent.setDataAndType(uri, "*/*"); 102 | return intent; 103 | } 104 | 105 | /** 106 | * 获取一个用于打开APK文件的intent 107 | * 108 | * @param context 上下文 109 | * @param filePath 文件的路径 110 | */ 111 | public static Intent getApkFileIntent(Context context, String filePath) { 112 | Intent intent = new Intent(); 113 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 114 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 115 | } 116 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 117 | intent.setAction(Intent.ACTION_VIEW); 118 | Uri uri = getUriForFile(context, new File(filePath)); 119 | intent.setDataAndType(uri, "application/vnd.android.package-archive"); 120 | return intent; 121 | } 122 | 123 | /** 124 | * 获取一个用于打开AUDIO文件的intent 125 | * 126 | * @param context 上下文 127 | * @param filePath 文件的路径 128 | */ 129 | public static Intent getAudioFileIntent(Context context, String filePath) { 130 | Intent intent = new Intent("android.intent.action.VIEW"); 131 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 132 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 133 | } 134 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 135 | intent.putExtra("oneshot", 0); 136 | intent.putExtra("configchange", 0); 137 | Uri uri = getUriForFile(context, new File(filePath)); 138 | intent.setDataAndType(uri, "audio/*"); 139 | return intent; 140 | } 141 | 142 | /** 143 | * 获取一个用于打开VIDEO文件的intent 144 | * 145 | * @param context 上下文 146 | * @param filePath 文件的路径 147 | */ 148 | public static Intent getVideoFileIntent(Context context, String filePath) { 149 | Intent intent = new Intent("android.intent.action.VIEW"); 150 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 151 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 152 | } 153 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 154 | intent.putExtra("oneshot", 0); 155 | intent.putExtra("configchange", 0); 156 | Uri uri = getUriForFile(context, new File(filePath)); 157 | intent.setDataAndType(uri, "video/*"); 158 | return intent; 159 | } 160 | 161 | /** 162 | * 获取一个用于打开HTML文件的intent 163 | * 164 | * @param context 上下文 165 | * @param filePath 文件的路径 166 | */ 167 | public static Intent getHtmlFileIntent(Context context, String filePath) { 168 | Intent intent = new Intent("android.intent.action.VIEW"); 169 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 170 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 171 | } 172 | Uri uri = getUriForFile(context, new File(filePath)).buildUpon() 173 | .encodedAuthority("com.android.htmlfileprovider") 174 | .scheme("content").encodedPath(filePath).build(); 175 | intent.setDataAndType(uri, "text/html"); 176 | return intent; 177 | } 178 | 179 | /** 180 | * 获取一个用于打开图片文件的intent 181 | * 182 | * @param context 上下文 183 | * @param filePath 文件的路径 184 | */ 185 | public static Intent getImageFileIntent(Context context, String filePath) { 186 | Intent intent = new Intent("android.intent.action.VIEW"); 187 | intent.addCategory("android.intent.category.DEFAULT"); 188 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 189 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 190 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 191 | } 192 | Uri uri = getUriForFile(context, new File(filePath)); 193 | intent.setDataAndType(uri, "image/*"); 194 | return intent; 195 | } 196 | 197 | /** 198 | * 获取一个用于打开PPT文件的intent 199 | * 200 | * @param context 上下文 201 | * @param filePath 文件的路径 202 | */ 203 | public static Intent getPptFileIntent(Context context, String filePath) { 204 | Intent intent = new Intent("android.intent.action.VIEW"); 205 | intent.addCategory("android.intent.category.DEFAULT"); 206 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 207 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 208 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 209 | } 210 | Uri uri = getUriForFile(context, new File(filePath)); 211 | intent.setDataAndType(uri, "application/vnd.ms-powerpoint"); 212 | return intent; 213 | } 214 | 215 | /** 216 | * 获取一个用于打开PPTX文件的intent 217 | * 218 | * @param context 上下文 219 | * @param filePath 文件的路径 220 | */ 221 | public static Intent getPptxFileIntent(Context context, String filePath) { 222 | Intent intent = new Intent("android.intent.action.VIEW"); 223 | intent.addCategory("android.intent.category.DEFAULT"); 224 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 225 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 226 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 227 | } 228 | Uri uri = getUriForFile(context, new File(filePath)); 229 | intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.presentationml.presentation"); 230 | return intent; 231 | } 232 | 233 | /** 234 | * 获取一个用于打开Excel文件的intent 235 | * 236 | * @param context 上下文 237 | * @param filePath 文件的路径 238 | */ 239 | public static Intent getExcelFileIntent(Context context, String filePath) { 240 | Intent intent = new Intent("android.intent.action.VIEW"); 241 | intent.addCategory("android.intent.category.DEFAULT"); 242 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 243 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 244 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 245 | } 246 | Uri uri = getUriForFile(context, new File(filePath)); 247 | intent.setDataAndType(uri, "application/vnd.ms-excel"); 248 | return intent; 249 | } 250 | 251 | /** 252 | * 获取一个用于打开XLSX文件的intent 253 | * 254 | * @param context 上下文 255 | * @param filePath 文件的路径 256 | */ 257 | public static Intent getXlsxFileIntent(Context context, String filePath) { 258 | Intent intent = new Intent("android.intent.action.VIEW"); 259 | intent.addCategory("android.intent.category.DEFAULT"); 260 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 261 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 262 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 263 | } 264 | Uri uri = getUriForFile(context, new File(filePath)); 265 | intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 266 | return intent; 267 | } 268 | 269 | /** 270 | * 获取一个用于打开Word文件的intent 271 | * 272 | * @param context 上下文 273 | * @param filePath 文件的路径 274 | */ 275 | public static Intent getWordFileIntent(Context context, String filePath) { 276 | Intent intent = new Intent("android.intent.action.VIEW"); 277 | intent.addCategory("android.intent.category.DEFAULT"); 278 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 279 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 280 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 281 | } 282 | Uri uri = getUriForFile(context, new File(filePath)); 283 | intent.setDataAndType(uri, "application/msword"); 284 | return intent; 285 | } 286 | 287 | /** 288 | * 获取一个用于打开DOCX文件的intent 289 | * 290 | * @param context 上下文 291 | * @param filePath 文件的路径 292 | */ 293 | public static Intent getDocxFileIntent(Context context, String filePath) { 294 | Intent intent = new Intent("android.intent.action.VIEW"); 295 | intent.addCategory("android.intent.category.DEFAULT"); 296 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 297 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 298 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 299 | } 300 | Uri uri = getUriForFile(context, new File(filePath)); 301 | intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); 302 | return intent; 303 | } 304 | 305 | /** 306 | * 获取一个用于打开CHM文件的intent 307 | * 308 | * @param context 上下文 309 | * @param filePath 文件的路径 310 | */ 311 | public static Intent getChmFileIntent(Context context, String filePath) { 312 | Intent intent = new Intent("android.intent.action.VIEW"); 313 | intent.addCategory("android.intent.category.DEFAULT"); 314 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 315 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 316 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 317 | } 318 | Uri uri = getUriForFile(context, new File(filePath)); 319 | intent.setDataAndType(uri, "application/x-chm"); 320 | return intent; 321 | } 322 | 323 | /** 324 | * 获取一个用于打开PDF文件的intent 325 | * 326 | * @param context 上下文 327 | * @param filePath 文件的路径 328 | */ 329 | public static Intent getPdfFileIntent(Context context, String filePath) { 330 | Intent intent = new Intent("android.intent.action.VIEW"); 331 | intent.addCategory("android.intent.category.DEFAULT"); 332 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 333 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 334 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 335 | } 336 | Uri uri = getUriForFile(context, new File(filePath)); 337 | intent.setDataAndType(uri, "application/pdf"); 338 | return intent; 339 | } 340 | 341 | /** 342 | * 获取一个用于打开文本文件的intent 343 | * 344 | * @param context 上下文 345 | * @param filePath 文件的路径 346 | * @param paramBoolean 是否打开本地文件 347 | */ 348 | public static Intent getTextFileIntent(Context context, String filePath, boolean paramBoolean) { 349 | Intent intent = new Intent("android.intent.action.VIEW"); 350 | intent.addCategory("android.intent.category.DEFAULT"); 351 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 352 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 353 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 354 | } 355 | if (paramBoolean) { 356 | Uri uri1 = getUriForFile(context, new File(filePath)); 357 | intent.setDataAndType(uri1, "text/plain"); 358 | } else { 359 | Uri uri2 = Uri.parse(filePath); 360 | intent.setDataAndType(uri2, "text/plain"); 361 | } 362 | return intent; 363 | } 364 | 365 | private static Uri getUriForFile(Context context, File file) { 366 | if (context == null || file == null) { 367 | throw new NullPointerException(); 368 | } 369 | Uri uri; 370 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 371 | uri = FileProvider.getUriForFile(context.getApplicationContext(), 372 | context.getApplicationContext().getPackageName() + ".provider", file); 373 | } else { 374 | uri = Uri.fromFile(file); 375 | } 376 | return uri; 377 | } 378 | 379 | } 380 | -------------------------------------------------------------------------------- /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/cb_light_selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /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/drawable/pb_horizontal.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_clear_cache.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 13 | 14 |