├── .gitignore ├── .gitlab-ci.yml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ ├── ExampleApp.html │ └── js │ │ └── ccnativeapi.js │ ├── java │ └── com │ │ └── luffyjet │ │ └── jsbridgeexample │ │ ├── ImagesResult.java │ │ ├── MainActivity.java │ │ ├── NetworkStauts.java │ │ ├── PathUtil.java │ │ └── handlers │ │ ├── DeviceInfoHandler.java │ │ └── ImageChooseHandler.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ ├── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml │ └── xml │ └── wjbconfig.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── webviewjsbridge.js │ └── java │ └── com │ └── luffyjet │ └── webviewjavascriptbridge │ ├── BridgeInterface.java │ ├── ConfigXmlParser.java │ ├── HandlerEntry.java │ ├── HandlerManager.java │ ├── JSResult.java │ ├── RequestHandler.java │ ├── Utils.java │ ├── WebViewJavaScriptBridge.java │ └── WebViewJavaScriptBridgeBase.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | /app/build 11 | /library/build 12 | 13 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | stages: 2 | - build 3 | - archive 4 | 5 | build_project: 6 | stage: build 7 | script: 8 | - gradle clean 9 | 10 | archive_project: 11 | stage: archive 12 | script: 13 | - gradle assembleRelease 14 | only: 15 | - master 16 | artifacts: 17 | paths: 18 | - app/build/outputs/apk/ -------------------------------------------------------------------------------- /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 2017 luffyjet 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 | WebViewJavascriptBridge 2 | ========================== 3 | 根据[IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge) 编写而来的JavascriptBridge。 4 | 5 | 6 | 相比同类库的优点: 7 | 1. 和[IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge) 一样的使用方法,可共用一套JS代码。 8 | 2. 同时也在此之上做了加强,参考了Cordova源码的模块管理,方便把各种不同的原生功能封装成独立的模块并统一管理。具体请看下面的 模块管理功能一栏。 9 | 10 | 规定JS和Java之间用标准JSON格式字符串交互,JS传给Java的数据会封装成 org.json.JSONObject。 11 | 12 | (An Android bridge for sending messages between Java and JavaScript in WebViews. Based on [IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge).) 13 | 14 | 15 | ### Gradle 16 | 17 | 18 | ```groovy 19 | repositories { 20 | jcenter() 21 | } 22 | 23 | compile 'com.luffyjet:webviewjavascriptbridge:1.0' 24 | ``` 25 | 26 | 27 | 28 | Examples 29 | -------- 30 | 31 | See the `app/` folder. 32 | 33 | 34 | 35 | Usage 36 | ----- 37 | 38 | 1) Init WebViewJavaScriptBridge 39 | 40 | ```java 41 | WebSettings settings = webView.getSettings(); 42 | settings.setJavaScriptEnabled(true);//很关键 43 | WebViewJavaScriptBridge mBridge = WebViewJavaScriptBridge.bridgeForWebView(this, webView); 44 | mBridge.setWebViewDelegate(new MyWebViewClient());//设置WebViewClient 45 | webView.setWebChromeClient(new MyChromeClient());//设置ChromeClient 46 | ``` 47 | 48 | 2) Register a handler in Java, and call a JS handler: 49 | 50 | ```java 51 | //注册一个 处理 js端发来消息的 handler 52 | mBridge.registerHandler("abs", new WebViewJavaScriptBridgeBase.WVJBHandler() { 53 | @Override 54 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) { 55 | Log.d(TAG, "from JS req: " + data.toString()); 56 | responseCallback.callback(new JSResult("i like milk from native").toJson()); 57 | } 58 | }); 59 | 60 | mBridge.callHandler("NativeCallJS", model.toJSON(), new WebViewJavaScriptBridgeBase.WVJBResponseCallback() { 61 | @Override 62 | public void callback(String responseData) { 63 | Log.d(TAG, "JS responded:" + responseData); 64 | Toast.makeText(MainActivity.this, "JS responded:" + responseData , Toast.LENGTH_SHORT).show(); 65 | } 66 | }); 67 | 68 | ``` 69 | 70 | 3) Copy and paste `setupWebViewJavascriptBridge` into your JS: 71 | 72 | ```javascript 73 | function setupWebViewJavascriptBridge(callback) { 74 | if(window.WebViewJavascriptBridge) { 75 | return callback(WebViewJavascriptBridge); 76 | } 77 | if(window.WVJBCallbacks) { 78 | return window.WVJBCallbacks.push(callback); 79 | } 80 | window.WVJBCallbacks = [callback]; 81 | var WVJBIframe = document.createElement('iframe'); 82 | WVJBIframe.style.display = 'none'; 83 | //这里最新IOS版是 https的scheme,真实环境下 需要判断iOS和Android,做下区分。 84 | WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'; 85 | document.documentElement.appendChild(WVJBIframe); 86 | setTimeout(function() { 87 | document.documentElement.removeChild(WVJBIframe) 88 | }, 0); 89 | } 90 | ``` 91 | 92 | 5) Finally, call `setupWebViewJavascriptBridge` and then use the bridge to register handlers and call Java handlers: 93 | 94 | ```javascript 95 | setupWebViewJavascriptBridge(function(bridge) { 96 | /* Initialize your app here */ 97 | 98 | bridge.registerHandler('NativeCallJS', function(data, responseCallback) { 99 | var responseData = { 100 | 'Javascript Says': 'Right back atcha!' 101 | }; 102 | 103 | log('Native call JS with ', data); 104 | responseCallback(responseData); 105 | }); 106 | 107 | var doc = document; 108 | var readyEvent = doc.createEvent('Events'); 109 | readyEvent.initEvent('WebViewJavascriptBridgeReady'); 110 | readyEvent.bridge = WebViewJavascriptBridge; 111 | doc.dispatchEvent(readyEvent); 112 | }); 113 | ``` 114 | 115 | 116 | ## 模块管理功能 117 | 可以和Cordova一样进行模块管理,同一种类型的消息(handler name相同)都由一个模块处理。 118 | 模块类需要继承 RequestHandler ,包含WebView的Activity要实现 BridgeInterface 接口。插件类由XML文件进行配置,请在项目中新建 res/xml/wjbconfig.xml 文件。 119 | 120 | ```java 121 | 122 | 123 | 124 | 127 | 130 | 131 | 132 | 133 | 136 | 139 | 140 | 141 | 142 | 143 | 144 | //一个简单的选图模块示例 145 | public class ImageChooseHandler extends RequestHandler { 146 | private static final String TAG = "ImageChooseHandler"; 147 | private static final int REQUEST_CODE_IMAGES = 100; 148 | private WebViewJavaScriptBridgeBase.WVJBResponseCallback mResponseCallback; 149 | 150 | @Override 151 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) { 152 | 153 | mResponseCallback = responseCallback; 154 | ... 155 | mBridgeInterface.startActivityForResult(this, Intent.createChooser(i, "选取图片"), REQUEST_CODE_IMAGES); 156 | } 157 | 158 | @Override 159 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 160 | if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGES) { 161 | try { 162 | ... 163 | mResponseCallback.callback(result.toJSON()); 164 | } catch (Exception e) { 165 | e.printStackTrace(); 166 | } 167 | } 168 | } 169 | } 170 | 171 | 172 | // 包含webview 的 WebActivity 173 | public class WebActivity extends AppCompatActivity implements BridgeInterface{ 174 | 175 | RequestHandler mRequestHandler; 176 | 177 | @Override 178 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 179 | super.onActivityResult(requestCode, resultCode, data); 180 | if (null != mRequestHandler) { 181 | RequestHandler callback = mRequestHandler; 182 | mRequestHandler = null; 183 | callback.onActivityResult(requestCode, resultCode, data); 184 | return; 185 | } 186 | 187 | //other code 188 | } 189 | 190 | @Override 191 | public void startActivityForResult(RequestHandler command, Intent intent, int requestCode) { 192 | setActivityResultCallback(command); 193 | startActivityForResult(intent, requestCode); 194 | } 195 | 196 | @Override 197 | public void setActivityResultCallback(RequestHandler plugin) { 198 | mRequestHandler = plugin; 199 | } 200 | 201 | @Override 202 | public Activity getActivity() { 203 | return this; 204 | } 205 | 206 | @Override 207 | public ExecutorService getThreadPool() { 208 | return Executors.newCachedThreadPool(new ThreadFactory() { 209 | @Override 210 | public Thread newThread(final Runnable r) { 211 | return new Thread(new Runnable() { 212 | @Override 213 | public void run() { 214 | android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 215 | r.run(); 216 | } 217 | },"Test"); 218 | } 219 | }); 220 | } 221 | } 222 | 223 | ``` 224 | 225 | 一个功能模块对应一个feature,feature name就是handle name。 onload属性为true代表模块(插件)会在webview初始化时一同初始化,false则是在需要该模块(插件)的时候通过反射加载。 226 | 227 | 具体使用方法请查看 ``app/`` 目录下的示例代码。 228 | 229 | 230 | ## Thanks 231 | [marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge) 232 | & [lzyzsd/JsBridge](https://github.com/lzyzsd/JsBridge) & [cordova-android](https://github.com/apache/cordova-android) 233 | 234 | 235 | 236 | License 237 | -------- 238 | 239 | See the [LICENSE](https://github.com/luffyjet/WebViewJavaScriptBridge/blob/master/LICENSE.md) file for license rights and limitations. -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion Integer.parseInt(rootProject.android_compileSdkVersion) 5 | buildToolsVersion rootProject.android_buildToolsVersion 6 | 7 | defaultConfig { 8 | applicationId rootProject.example_package 9 | minSdkVersion Integer.parseInt(rootProject.android_minSdkVersion) 10 | targetSdkVersion Integer.parseInt(rootProject.android_targetSdkVersion) 11 | versionCode Integer.parseInt(rootProject.android_versionCode) 12 | versionName rootProject.android_versionName 13 | } 14 | 15 | 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | compile "com.android.support:appcompat-v7:${android_support}" 27 | compile "com.google.code.gson:gson:${android_gson}" 28 | // compile project(':library') 29 | compile 'com.luffyjet:webviewjavascriptbridge:1.0' 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/luffyjet/Documents/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /app/src/main/assets/ExampleApp.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 30 | 31 | 32 | 33 | 90 | 91 | 92 | 93 |

WebViewJavascriptBridge Demo

94 |
95 |
96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /app/src/main/assets/js/ccnativeapi.js: -------------------------------------------------------------------------------- 1 | ;(function() { 2 | window.onerror = function(err) { 3 | console.log("page on error:" + err); 4 | }; 5 | 6 | var browserType = { 7 | types: function() { 8 | var u = window.navigator.userAgent, 9 | app = window.navigator.appVersion; 10 | return { //移动终端浏览器版本信息 11 | trident: u.indexOf('Trident') > -1, //IE内核 12 | presto: u.indexOf('Presto') > -1, //opera内核 13 | webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 14 | gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 15 | mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端 16 | mac: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 17 | android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 18 | iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器 19 | iPad: u.indexOf('iPad') > -1, //是否iPad 20 | webApp: u.indexOf('Safari') == -1 //是否web应该程序,没有头部与底部 21 | 22 | }; 23 | }(), 24 | 25 | language: (window.navigator.browserLanguage || window.navigator.language).toLowerCase() 26 | }; 27 | 28 | function setupWebViewJavascriptBridge(callback) { 29 | if(window.WebViewJavascriptBridge) { 30 | return callback(WebViewJavascriptBridge); 31 | } 32 | if(window.WVJBCallbacks) { 33 | return window.WVJBCallbacks.push(callback); 34 | } 35 | window.WVJBCallbacks = [callback]; 36 | var WVJBIframe = document.createElement('iframe'); 37 | WVJBIframe.style.display = 'none'; 38 | if(browserType.types.android) { 39 | WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'; 40 | } else if(browserType.types.mac || browserType.types.iPhone || browserType.types.iPad) { 41 | WVJBIframe.src = 'https://__bridge_loaded__'; 42 | } 43 | document.documentElement.appendChild(WVJBIframe); 44 | setTimeout(function() { 45 | document.documentElement.removeChild(WVJBIframe) 46 | }, 0); 47 | } 48 | 49 | function invoke(handlerName, data, callback) { 50 | if(window.WebViewJavascriptBridge) { 51 | window.WebViewJavascriptBridge.callHandler(handlerName, data, callback); 52 | } else { 53 | document.addEventListener( 54 | 'WebViewJavascriptBridgeReady', 55 | function() { 56 | window.WebViewJavascriptBridge.callHandler(handlerName, data, callback); 57 | }, 58 | false 59 | ); 60 | } 61 | } 62 | 63 | setupWebViewJavascriptBridge(function(bridge) { 64 | bridge.registerHandler('NativeCallJS', function(data, responseCallback) { 65 | var responseData = { 66 | 'Javascript Says': 'Right back atcha!' 67 | }; 68 | 69 | log('Native call JS with ', data); 70 | responseCallback(responseData); 71 | }); 72 | 73 | var doc = document; 74 | var readyEvent = doc.createEvent('Events'); 75 | readyEvent.initEvent('WebViewJavascriptBridgeReady'); 76 | readyEvent.bridge = WebViewJavascriptBridge; 77 | doc.dispatchEvent(readyEvent); 78 | }); 79 | 80 | 81 | window.ccapi = { 82 | //设备信息 83 | deviceInfo: function(data) { 84 | invoke("deviceInfo", { 85 | 'full': data.full 86 | }, data.success); 87 | }, 88 | 89 | //选择图片 90 | chooseImage: function(data) { 91 | invoke("chooseImage", { 92 | 'count': data.count, 93 | 'sizeType': data.sizeType, 94 | 'sourceType': data.sourceType 95 | }, data.success); 96 | } 97 | 98 | }; 99 | })(); -------------------------------------------------------------------------------- /app/src/main/java/com/luffyjet/jsbridgeexample/ImagesResult.java: -------------------------------------------------------------------------------- 1 | package com.luffyjet.jsbridgeexample; 2 | 3 | import com.google.gson.Gson; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Title : 9 | * Author : luffyjet 10 | * Date : 2016/12/20 11 | * Project : branch_1009 12 | * Site : http://www.luffyjet.com 13 | */ 14 | 15 | public class ImagesResult { 16 | public List localIds; 17 | public boolean status; 18 | public ImagesResult(boolean b) { 19 | status = b; 20 | } 21 | 22 | public String toJSON() { 23 | return new Gson().toJson(this); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/luffyjet/jsbridgeexample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.luffyjet.jsbridgeexample; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.graphics.Bitmap; 6 | import android.net.Uri; 7 | import android.os.Bundle; 8 | import android.os.Process; 9 | import android.support.v7.app.AppCompatActivity; 10 | import android.util.Log; 11 | import android.view.View; 12 | import android.webkit.ValueCallback; 13 | import android.webkit.WebChromeClient; 14 | import android.webkit.WebSettings; 15 | import android.webkit.WebView; 16 | import android.webkit.WebViewClient; 17 | import android.widget.Button; 18 | import android.widget.Toast; 19 | 20 | import com.google.gson.Gson; 21 | import com.luffyjet.webviewjavascriptbridge.BridgeInterface; 22 | import com.luffyjet.webviewjavascriptbridge.JSResult; 23 | import com.luffyjet.webviewjavascriptbridge.RequestHandler; 24 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridge; 25 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridgeBase; 26 | 27 | import org.json.JSONObject; 28 | 29 | import java.util.concurrent.ExecutorService; 30 | import java.util.concurrent.Executors; 31 | import java.util.concurrent.ThreadFactory; 32 | 33 | public class MainActivity extends AppCompatActivity implements BridgeInterface{ 34 | private static final String TAG = MainActivity.class.getSimpleName(); 35 | WebViewJavaScriptBridge mBridge; 36 | RequestHandler mRequestHandler; 37 | 38 | @Override 39 | protected void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | setContentView(R.layout.activity_main); 42 | initView(); 43 | } 44 | 45 | private void initView() { 46 | if (mBridge != null) { 47 | return; 48 | } 49 | 50 | final WebView webView = (WebView) findViewById(R.id.webview); 51 | Button callJsBtn = (Button) findViewById(R.id.button); 52 | Button disableTimeoutBtn = (Button) findViewById(R.id.disable_timeout); 53 | Button refreshBtn = (Button) findViewById(R.id.refresh); 54 | 55 | 56 | //Start 初始化 WebViewJavaScriptBridge 57 | WebViewJavaScriptBridge.enableLogging();//打印Log 58 | WebSettings settings = webView.getSettings(); 59 | settings.setJavaScriptEnabled(true);//很关键 60 | mBridge = WebViewJavaScriptBridge.bridgeForWebView(this, webView); 61 | mBridge.setWebViewDelegate(new MyWebViewClient());//设置WebViewClient 62 | webView.setWebChromeClient(new MyChromeClient());//设置ChromeClient 63 | //End 64 | 65 | 66 | callJsBtn.setOnClickListener(new View.OnClickListener() { 67 | @Override 68 | public void onClick(View v) { 69 | //向js端发送消息 70 | callHandler(); 71 | } 72 | }); 73 | 74 | //注册一个 处理 js端发来消息的 handler 75 | mBridge.registerHandler("abs", new WebViewJavaScriptBridgeBase.WVJBHandler() { 76 | @Override 77 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) { 78 | Log.d(TAG, "from JS req: " + data.toString()); 79 | responseCallback.callback(new JSResult("i like milk from native").toJson()); 80 | } 81 | }); 82 | 83 | 84 | disableTimeoutBtn.setOnClickListener(new View.OnClickListener() { 85 | @Override 86 | public void onClick(View v) { 87 | disableSafetyTimeout(); 88 | } 89 | }); 90 | 91 | refreshBtn.setOnClickListener(new View.OnClickListener() { 92 | @Override 93 | public void onClick(View v) { 94 | webView.reload(); 95 | } 96 | }); 97 | 98 | // webView.loadUrl("http://192.168.118.55:8090/spittr/ExampleApp.html"); 99 | 100 | webView.loadUrl("file:///android_asset/ExampleApp.html"); 101 | } 102 | 103 | @Override 104 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 105 | super.onActivityResult(requestCode, resultCode, data); 106 | if (null != mRequestHandler) { 107 | RequestHandler callback = mRequestHandler; 108 | mRequestHandler = null; 109 | callback.onActivityResult(requestCode, resultCode, data); 110 | return; 111 | } 112 | 113 | //other code 114 | } 115 | 116 | @Override 117 | public void startActivityForResult(RequestHandler command, Intent intent, int requestCode) { 118 | setActivityResultCallback(command); 119 | startActivityForResult(intent, requestCode); 120 | } 121 | 122 | @Override 123 | public void setActivityResultCallback(RequestHandler plugin) { 124 | mRequestHandler = plugin; 125 | } 126 | 127 | @Override 128 | public Activity getActivity() { 129 | return this; 130 | } 131 | 132 | @Override 133 | public ExecutorService getThreadPool() { 134 | return Executors.newCachedThreadPool(new ThreadFactory() { 135 | @Override 136 | public Thread newThread(final Runnable r) { 137 | return new Thread(new Runnable() { 138 | @Override 139 | public void run() { 140 | android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 141 | r.run(); 142 | } 143 | },"Test"); 144 | } 145 | }); 146 | } 147 | 148 | 149 | /** 150 | * 发送消息给JS端 151 | */ 152 | void callHandler() { 153 | Model model = new Model(); 154 | model.name = "lucy"; 155 | model.age = 18; 156 | model.msg = "Hi there, JS!"; 157 | 158 | mBridge.callHandler("NativeCallJS", model.toJSON(), new WebViewJavaScriptBridgeBase.WVJBResponseCallback() { 159 | @Override 160 | public void callback(String responseData) { 161 | Log.d(TAG, "JS responded:" + responseData); 162 | Toast.makeText(MainActivity.this, "JS responded:" + responseData , Toast.LENGTH_SHORT).show(); 163 | } 164 | }); 165 | } 166 | 167 | void disableSafetyTimeout() { 168 | mBridge.disableJavscriptAlertBoxSafetyTimeout(); 169 | } 170 | 171 | class MyChromeClient extends WebChromeClient { 172 | 173 | // Android < 3.0 174 | public void openFileChooser(ValueCallback uploadMsg) { 175 | //choose image or take photo 176 | } 177 | 178 | // Android > 3.0 179 | public void openFileChooser(ValueCallback uploadMsg, String acceptType) { 180 | openFileChooser(uploadMsg); 181 | } 182 | 183 | // Android > 4.1.1 184 | public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) { 185 | openFileChooser(uploadMsg); 186 | } 187 | 188 | //Android >= 5.0 189 | @Override 190 | public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) { 191 | //choose image or take photo 192 | return true; 193 | } 194 | } 195 | 196 | class MyWebViewClient extends WebViewClient { 197 | @Override 198 | public void onPageStarted(WebView view, String url, Bitmap favicon) { 199 | super.onPageStarted(view, url, favicon); 200 | Log.i(TAG, "onPageStarted"); 201 | } 202 | 203 | 204 | @Override 205 | public void onPageFinished(WebView view, String url) { 206 | super.onPageFinished(view, url); 207 | Log.i(TAG, "onPageFinished"); 208 | } 209 | 210 | 211 | @Override 212 | public boolean shouldOverrideUrlLoading(WebView view, String url) { 213 | Log.i(TAG, "shouldOverrideUrlLoading"); 214 | return super.shouldOverrideUrlLoading(view, url); 215 | } 216 | } 217 | 218 | static class Model { 219 | String name; 220 | int age; 221 | String msg; 222 | 223 | @Override 224 | public String toString() { 225 | return toJSON(); 226 | } 227 | 228 | public String toJSON() { 229 | return new Gson().toJson(this); 230 | } 231 | } 232 | 233 | } 234 | -------------------------------------------------------------------------------- /app/src/main/java/com/luffyjet/jsbridgeexample/NetworkStauts.java: -------------------------------------------------------------------------------- 1 | package com.luffyjet.jsbridgeexample; 2 | 3 | import android.content.Context; 4 | import android.net.ConnectivityManager; 5 | import android.net.NetworkInfo; 6 | import android.telephony.TelephonyManager; 7 | 8 | 9 | public class NetworkStauts { 10 | private static final int NETWORK_TYPE_UNAVAILABLE = -1; 11 | private static final int NETWORK_TYPE_WIFI = -101; 12 | 13 | private static final int NETWORK_CLASS_WIFI = -101; 14 | private static final int NETWORK_CLASS_UNAVAILABLE = -1; 15 | /** Unknown network class. */ 16 | private static final int NETWORK_CLASS_UNKNOWN = 0; 17 | /** Class of broadly defined "2G" networks. */ 18 | private static final int NETWORK_CLASS_2_G = 1; 19 | /** Class of broadly defined "3G" networks. */ 20 | private static final int NETWORK_CLASS_3_G = 2; 21 | /** Class of broadly defined "4G" networks. */ 22 | private static final int NETWORK_CLASS_4_G = 3; 23 | 24 | // 适配低版本手机 25 | /** Network type is unknown */ 26 | public static final int NETWORK_TYPE_UNKNOWN = 0; 27 | /** Current network is GPRS */ 28 | public static final int NETWORK_TYPE_GPRS = 1; 29 | /** Current network is EDGE */ 30 | public static final int NETWORK_TYPE_EDGE = 2; 31 | /** Current network is UMTS */ 32 | public static final int NETWORK_TYPE_UMTS = 3; 33 | /** Current network is CDMA: Either IS95A or IS95B */ 34 | public static final int NETWORK_TYPE_CDMA = 4; 35 | /** Current network is EVDO revision 0 */ 36 | public static final int NETWORK_TYPE_EVDO_0 = 5; 37 | /** Current network is EVDO revision A */ 38 | public static final int NETWORK_TYPE_EVDO_A = 6; 39 | /** Current network is 1xRTT */ 40 | public static final int NETWORK_TYPE_1xRTT = 7; 41 | /** Current network is HSDPA */ 42 | public static final int NETWORK_TYPE_HSDPA = 8; 43 | /** Current network is HSUPA */ 44 | public static final int NETWORK_TYPE_HSUPA = 9; 45 | /** Current network is HSPA */ 46 | public static final int NETWORK_TYPE_HSPA = 10; 47 | /** Current network is iDen */ 48 | public static final int NETWORK_TYPE_IDEN = 11; 49 | /** Current network is EVDO revision B */ 50 | public static final int NETWORK_TYPE_EVDO_B = 12; 51 | /** Current network is LTE */ 52 | public static final int NETWORK_TYPE_LTE = 13; 53 | /** Current network is eHRPD */ 54 | public static final int NETWORK_TYPE_EHRPD = 14; 55 | /** Current network is HSPA+ */ 56 | public static final int NETWORK_TYPE_HSPAP = 15; 57 | 58 | 59 | /** 60 | * 获取网络类型 61 | * @return 62 | */ 63 | public static String getCurrentNetworkType(Context context) { 64 | int networkClass = getNetworkClass(context); 65 | String type = "unknown"; 66 | switch (networkClass) { 67 | case NETWORK_CLASS_UNAVAILABLE: 68 | type = "none"; 69 | break; 70 | case NETWORK_CLASS_WIFI: 71 | type = "Wi-Fi"; 72 | break; 73 | case NETWORK_CLASS_2_G: 74 | type = "2G"; 75 | break; 76 | case NETWORK_CLASS_3_G: 77 | type = "3G"; 78 | break; 79 | case NETWORK_CLASS_4_G: 80 | type = "4G"; 81 | break; 82 | case NETWORK_CLASS_UNKNOWN: 83 | type = "unknown"; 84 | break; 85 | } 86 | return type; 87 | } 88 | 89 | private static int getNetworkClassByType(int networkType) { 90 | switch (networkType) { 91 | case NETWORK_TYPE_UNAVAILABLE: 92 | return NETWORK_CLASS_UNAVAILABLE; 93 | case NETWORK_TYPE_WIFI: 94 | return NETWORK_CLASS_WIFI; 95 | case NETWORK_TYPE_GPRS: 96 | case NETWORK_TYPE_EDGE: 97 | case NETWORK_TYPE_CDMA: 98 | case NETWORK_TYPE_1xRTT: 99 | case NETWORK_TYPE_IDEN: 100 | return NETWORK_CLASS_2_G; 101 | case NETWORK_TYPE_UMTS: 102 | case NETWORK_TYPE_EVDO_0: 103 | case NETWORK_TYPE_EVDO_A: 104 | case NETWORK_TYPE_HSDPA: 105 | case NETWORK_TYPE_HSUPA: 106 | case NETWORK_TYPE_HSPA: 107 | case NETWORK_TYPE_EVDO_B: 108 | case NETWORK_TYPE_EHRPD: 109 | case NETWORK_TYPE_HSPAP: 110 | return NETWORK_CLASS_3_G; 111 | case NETWORK_TYPE_LTE: 112 | return NETWORK_CLASS_4_G; 113 | default: 114 | return NETWORK_CLASS_UNKNOWN; 115 | } 116 | } 117 | 118 | 119 | private static int getNetworkClass(Context context) { 120 | int networkType = NETWORK_TYPE_UNKNOWN; 121 | try { 122 | final NetworkInfo network = ((ConnectivityManager) context 123 | .getSystemService(Context.CONNECTIVITY_SERVICE)) 124 | .getActiveNetworkInfo(); 125 | if (network != null && network.isAvailable() 126 | && network.isConnected()) { 127 | int type = network.getType(); 128 | if (type == ConnectivityManager.TYPE_WIFI) { 129 | networkType = NETWORK_TYPE_WIFI; 130 | } else if (type == ConnectivityManager.TYPE_MOBILE) { 131 | TelephonyManager telephonyManager = (TelephonyManager) context 132 | .getSystemService(Context.TELEPHONY_SERVICE); 133 | networkType = telephonyManager.getNetworkType(); 134 | } 135 | } else { 136 | networkType = NETWORK_TYPE_UNAVAILABLE; 137 | } 138 | 139 | } catch (Exception ex) { 140 | ex.printStackTrace(); 141 | } 142 | return getNetworkClassByType(networkType); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /app/src/main/java/com/luffyjet/jsbridgeexample/PathUtil.java: -------------------------------------------------------------------------------- 1 | package com.luffyjet.jsbridgeexample; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Activity; 5 | import android.content.ContentUris; 6 | import android.content.Context; 7 | import android.database.Cursor; 8 | import android.net.Uri; 9 | import android.os.Environment; 10 | import android.provider.DocumentsContract; 11 | import android.provider.MediaStore; 12 | 13 | public class PathUtil { 14 | /** 15 | * 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换 16 | * @param context 17 | * @param imageUri 18 | * @author yaoxing 19 | * @date 2014-10-12 20 | */ 21 | @TargetApi(19) 22 | public static String getImageAbsolutePath(Activity context, Uri imageUri) { 23 | if (context == null || imageUri == null) 24 | return null; 25 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) { 26 | if (isExternalStorageDocument(imageUri)) { 27 | String docId = DocumentsContract.getDocumentId(imageUri); 28 | String[] split = docId.split(":"); 29 | String type = split[0]; 30 | if ("primary".equalsIgnoreCase(type)) { 31 | return Environment.getExternalStorageDirectory() + "/" + split[1]; 32 | } 33 | } else if (isDownloadsDocument(imageUri)) { 34 | String id = DocumentsContract.getDocumentId(imageUri); 35 | Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); 36 | return getDataColumn(context, contentUri, null, null); 37 | } else if (isMediaDocument(imageUri)) { 38 | String docId = DocumentsContract.getDocumentId(imageUri); 39 | String[] split = docId.split(":"); 40 | String type = split[0]; 41 | Uri contentUri = null; 42 | if ("image".equals(type)) { 43 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 44 | } else if ("video".equals(type)) { 45 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; 46 | } else if ("audio".equals(type)) { 47 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 48 | } 49 | String selection = MediaStore.Images.Media._ID + "=?"; 50 | String[] selectionArgs = new String[]{split[1]}; 51 | return getDataColumn(context, contentUri, selection, selectionArgs); 52 | } 53 | } // MediaStore (and general) 54 | else if ("content".equalsIgnoreCase(imageUri.getScheme())) { 55 | // Return the remote address 56 | if (isGooglePhotosUri(imageUri)) 57 | return imageUri.getLastPathSegment(); 58 | return getDataColumn(context, imageUri, null, null); 59 | } 60 | // File 61 | else if ("file".equalsIgnoreCase(imageUri.getScheme())) { 62 | return imageUri.getPath(); 63 | } 64 | return null; 65 | } 66 | 67 | public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { 68 | Cursor cursor = null; 69 | String column = MediaStore.Images.Media.DATA; 70 | String[] projection = {column}; 71 | try { 72 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); 73 | if (cursor != null && cursor.moveToFirst()) { 74 | int index = cursor.getColumnIndexOrThrow(column); 75 | return cursor.getString(index); 76 | } 77 | } finally { 78 | if (cursor != null) 79 | cursor.close(); 80 | } 81 | return null; 82 | } 83 | 84 | /** 85 | * @param uri The Uri to check. 86 | * @return Whether the Uri authority is ExternalStorageProvider. 87 | */ 88 | public static boolean isExternalStorageDocument(Uri uri) { 89 | return "com.android.externalstorage.documents".equals(uri.getAuthority()); 90 | } 91 | 92 | /** 93 | * @param uri The Uri to check. 94 | * @return Whether the Uri authority is DownloadsProvider. 95 | */ 96 | public static boolean isDownloadsDocument(Uri uri) { 97 | return "com.android.providers.downloads.documents".equals(uri.getAuthority()); 98 | } 99 | 100 | /** 101 | * @param uri The Uri to check. 102 | * @return Whether the Uri authority is MediaProvider. 103 | */ 104 | public static boolean isMediaDocument(Uri uri) { 105 | return "com.android.providers.media.documents".equals(uri.getAuthority()); 106 | } 107 | 108 | /** 109 | * @param uri The Uri to check. 110 | * @return Whether the Uri authority is Google Photos. 111 | */ 112 | public static boolean isGooglePhotosUri(Uri uri) { 113 | return "com.google.android.apps.photos.content".equals(uri.getAuthority()); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /app/src/main/java/com/luffyjet/jsbridgeexample/handlers/DeviceInfoHandler.java: -------------------------------------------------------------------------------- 1 | package com.luffyjet.jsbridgeexample.handlers; 2 | 3 | import android.content.Context; 4 | import android.content.pm.PackageInfo; 5 | import android.content.pm.PackageManager; 6 | import android.os.Build; 7 | import android.telephony.TelephonyManager; 8 | 9 | import com.google.gson.Gson; 10 | import com.luffyjet.jsbridgeexample.NetworkStauts; 11 | import com.luffyjet.jsbridgeexample.R; 12 | import com.luffyjet.webviewjavascriptbridge.RequestHandler; 13 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridgeBase; 14 | 15 | import org.json.JSONObject; 16 | 17 | /** 18 | * Title : 19 | * Author : luffyjet 20 | * Date : 2016/12/19 21 | * Project : WebViewJavaScriptBridge 22 | * Site : http://www.luffyjet.com 23 | */ 24 | 25 | public class DeviceInfoHandler extends RequestHandler { 26 | 27 | @Override 28 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) { 29 | log(getHandlerName(), data.toString()); 30 | responseCallback.callback(new DeviceInfo().toJson(mContext)); 31 | } 32 | 33 | 34 | private static class DeviceInfo { 35 | 36 | String appName;//应用名称 37 | String appVersion;//CC+版本号 38 | String systemType;//系统类型 39 | String systemVersion;//版本 40 | String version;//JS桥接引擎版本 41 | String deviceModel;//设备型号,字符串类型 42 | String deviceName;//设备名称,字符串类型 43 | String operator;//运营商名称,若未获取到则返回none,字符串类型 44 | 45 | /** 46 | * 网络类型,字符串类型 47 | * 48 | * unknown //未知 49 | * wifi //wifi 50 | * 2g //2G网络 51 | * 3g //3G网络 52 | * 4g //4G网络 53 | * none //无网络 54 | */ 55 | public String connectionType;// 56 | 57 | 58 | String toJson(Context context) { 59 | try { 60 | appName = context.getString(R.string.app_name); 61 | systemType = "Android"; 62 | systemVersion = Build.VERSION.RELEASE; 63 | version = "1.0"; 64 | deviceModel = Build.MODEL; 65 | deviceName = Build.PRODUCT; 66 | 67 | PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); 68 | appVersion = pi.versionName; 69 | 70 | TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 71 | operator = telephonyManager.getSimOperatorName(); 72 | 73 | connectionType = NetworkStauts.getCurrentNetworkType(context); 74 | } catch (PackageManager.NameNotFoundException e) { 75 | e.printStackTrace(); 76 | } 77 | 78 | return new Gson().toJson(this); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /app/src/main/java/com/luffyjet/jsbridgeexample/handlers/ImageChooseHandler.java: -------------------------------------------------------------------------------- 1 | package com.luffyjet.jsbridgeexample.handlers; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.util.Log; 6 | 7 | import com.luffyjet.jsbridgeexample.ImagesResult; 8 | import com.luffyjet.jsbridgeexample.PathUtil; 9 | import com.luffyjet.webviewjavascriptbridge.RequestHandler; 10 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridge; 11 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridgeBase; 12 | 13 | import org.json.JSONObject; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * Title : 20 | * Author : luffyjet 21 | * Date : 2016/12/16 22 | * Project : WebViewJavaScriptBridge 23 | * Site : http://www.luffyjet.com 24 | */ 25 | 26 | public class ImageChooseHandler extends RequestHandler { 27 | private static final String TAG = "ImageChooseHandler"; 28 | private static final int REQUEST_CODE_IMAGES = 100; 29 | private WebViewJavaScriptBridgeBase.WVJBResponseCallback mResponseCallback; 30 | 31 | @Override 32 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) { 33 | log(getHandlerName(), data.toString()); 34 | mResponseCallback = responseCallback; 35 | 36 | int count = 0; 37 | 38 | try { 39 | count = data.optInt("count"); 40 | } catch (Exception e) { 41 | e.printStackTrace(); 42 | } 43 | 44 | if (count == 0) { 45 | count = 9; 46 | } 47 | 48 | //这里只选取一张,真实情况下,可以通过自定义的选图界面,选择复数的图片,并返回给JS 49 | Intent i = new Intent(Intent.ACTION_GET_CONTENT); 50 | i.addCategory(Intent.CATEGORY_OPENABLE); 51 | i.setType("image/*"); 52 | mBridgeInterface.startActivityForResult(this, Intent.createChooser(i, "选取图片"), REQUEST_CODE_IMAGES); 53 | } 54 | 55 | @Override 56 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 57 | if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGES) { 58 | Log.i(TAG, "onActivityResult: " + data.getData()); 59 | try { 60 | //根据Uri 获取真实路径 61 | String path = PathUtil.getImageAbsolutePath(mBridgeInterface.getActivity(), data.getData()); 62 | Log.i(TAG, "onActivityResult: " + path); 63 | ImagesResult result = new ImagesResult(true); 64 | List ids = new ArrayList<>(); 65 | //在真实路径之前添加特殊SCHEMA,在WebViewClient.shouldInterceptRequest方法里做资源替换,将图片显示出来 66 | //具体可查看WebViewJavaScriptBridge的源码 67 | ids.add(WebViewJavaScriptBridge.LOCAL_FILE_SCHEMA + path); 68 | result.localIds = ids; 69 | mResponseCallback.callback(result.toJSON()); 70 | 71 | } catch (Exception e) { 72 | e.printStackTrace(); 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 16 | 17 | 20 | 21 |