├── .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 |
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
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
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
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 | *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 | *millis <= 0, return null
295 | * @param precision The precision of time span. 296 | *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
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 | * 文本帮助类
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
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 |