Skip to content

Commit a863e12

Browse files
luffyjetluffyjet
luffyjet
authored and
luffyjet
committed
完善示例和Readme
1 parent e72b561 commit a863e12

File tree

14 files changed

+446
-299
lines changed

14 files changed

+446
-299
lines changed

README.md

Lines changed: 164 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,164 @@
1-
## Android与JS通信桥接框架
2-
可以与[IOS版WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge)公用一套前端JS代码
1+
WebViewJavascriptBridge
2+
==========================
3+
根据[IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge) 编写而来的JavascriptBridge,这样一来前端可以公用一套JS代码。使用方法和 marcuswestin/WebViewJavascriptBridge 也是基本一样。
4+
5+
同时也在此之上做了加强,根据Cordova的源码,将每一种消息封装成一个插件(RequestHandler),并统一管理起来(HandlerManager)。
6+
7+
An Android bridge for sending messages between Java and JavaScript in WebViews. Based on [IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge).
8+
9+
10+
### Gradle
11+
12+
13+
```groovy
14+
repositories {
15+
jcenter()
16+
}
17+
18+
compile 'com.luffyjet:webviewjavascriptbridge:1.0'
19+
```
20+
21+
22+
23+
Examples
24+
--------
25+
26+
See the `app/` folder.
27+
28+
29+
30+
Usage
31+
-----
32+
33+
1)
34+
35+
```java
36+
WebSettings settings = webView.getSettings();
37+
settings.setJavaScriptEnabled(true);//很关键
38+
WebViewJavaScriptBridge mBridge = WebViewJavaScriptBridge.bridgeForWebView(this, webView);
39+
mBridge.setWebViewDelegate(new MyWebViewClient());//设置WebViewClient
40+
webView.setWebChromeClient(new MyChromeClient());//设置ChromeClient
41+
```
42+
43+
2) Register a handler in Java, and call a JS handler:
44+
45+
```java
46+
//注册一个 处理 js端发来消息的 handler
47+
mBridge.registerHandler("abs", new WebViewJavaScriptBridgeBase.WVJBHandler() {
48+
@Override
49+
public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
50+
Log.d(TAG, "from JS req: " + data.toString());
51+
responseCallback.callback(new JSResult("i like milk from native").toJson());
52+
}
53+
});
54+
55+
mBridge.callHandler("NativeCallJS", model.toJSON(), new WebViewJavaScriptBridgeBase.WVJBResponseCallback() {
56+
@Override
57+
public void callback(String responseData) {
58+
Log.d(TAG, "JS responded:" + responseData);
59+
Toast.makeText(MainActivity.this, "JS responded:" + responseData , Toast.LENGTH_SHORT).show();
60+
}
61+
});
62+
63+
```
64+
65+
3) Copy and paste `setupWebViewJavascriptBridge` into your JS:
66+
67+
```javascript
68+
function setupWebViewJavascriptBridge(callback) {
69+
if(window.WebViewJavascriptBridge) {
70+
return callback(WebViewJavascriptBridge);
71+
}
72+
if(window.WVJBCallbacks) {
73+
return window.WVJBCallbacks.push(callback);
74+
}
75+
window.WVJBCallbacks = [callback];
76+
var WVJBIframe = document.createElement('iframe');
77+
WVJBIframe.style.display = 'none';
78+
WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
79+
document.documentElement.appendChild(WVJBIframe);
80+
setTimeout(function() {
81+
document.documentElement.removeChild(WVJBIframe)
82+
}, 0);
83+
}
84+
```
85+
86+
5) Finally, call `setupWebViewJavascriptBridge` and then use the bridge to register handlers and call Java handlers:
87+
88+
```javascript
89+
setupWebViewJavascriptBridge(function(bridge) {
90+
/* Initialize your app here */
91+
92+
bridge.registerHandler('NativeCallJS', function(data, responseCallback) {
93+
var responseData = {
94+
'Javascript Says': 'Right back atcha!'
95+
};
96+
97+
log('Native call JS with ', data);
98+
responseCallback(responseData);
99+
});
100+
101+
var doc = document;
102+
var readyEvent = doc.createEvent('Events');
103+
readyEvent.initEvent('WebViewJavascriptBridgeReady');
104+
readyEvent.bridge = WebViewJavascriptBridge;
105+
doc.dispatchEvent(readyEvent);
106+
});
107+
```
108+
109+
110+
## 插件管理功能
111+
可以和Cordova一样进行插件管理,每一种类型的消息都由一个插件管理。
112+
插件类继承至 RequestHandler ,包含WebView的Activity要实现 BridgeInterface 接口。插件类由XML文件进行配置,请新建 res/xml/wjbconfig.xml 文件。
113+
114+
```
115+
<?xml version="1.0" encoding="utf-8"?>
116+
<widget>
117+
<feature name="chooseImage">
118+
<param
119+
name="android-package"
120+
value="com.luffyjet.jsbridgeexample.handlers.ImageChooseHandler"/>
121+
<param
122+
name="onload"
123+
value="true"/>
124+
</feature>
125+
126+
<feature name="deviceInfo">
127+
<param
128+
name="android-package"
129+
value="com.luffyjet.jsbridgeexample.handlers.DeviceInfoHandler"/>
130+
<param
131+
name="onload"
132+
value="true"/>
133+
</feature>
134+
135+
</widget>
136+
```
137+
138+
一个插件对应一个feature,feature name就是handle name。 onload属性为true代表插件会在webview初始化时一同初始化,false则是在需要该插件的时候通过反射加载。
139+
140+
具体使用方法请查看 ``app/`` 目录下的示例代码。
141+
142+
143+
## Thanks
144+
[marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge)
145+
& [cordova-android](https://github.com/apache/cordova-android)
146+
147+
148+
149+
License
150+
--------
151+
152+
Copyright 2017 luffyjet.
153+
154+
Licensed under the Apache License, Version 2.0 (the "License");
155+
you may not use this file except in compliance with the License.
156+
You may obtain a copy of the License at
157+
158+
http://www.apache.org/licenses/LICENSE-2.0
159+
160+
Unless required by applicable law or agreed to in writing, software
161+
distributed under the License is distributed on an "AS IS" BASIS,
162+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
163+
See the License for the specific language governing permissions and
164+
limitations under the License.

app/build.gradle

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,10 @@ android {
1313
}
1414

1515

16-
signingConfigs {
17-
release {
18-
storeFile file('keystore.jks')
19-
storePassword "123456"
20-
keyAlias "lzcapp"
21-
keyPassword "123456"
22-
v2SigningEnabled false//渠道包工具需要
23-
// MD5: BF:A5:17:1C:32:6C:9E:87:CB:3E:E9:57:11:70:EB:3F
24-
// SHA1: 5C:A3:C5:2C:A1:FA:DA:8C:E9:44:96:7D:79:B7:5B:4D:F8:7E:17:EE
25-
// SHA256: F9:6D:2F:90:F3:C4:1A:B4:C5:6B:87:FD:15:11:CE:EA:AE:65:AD:B5:84:6E:D6:A1:D7:2E:BA:80:FF:FC:ED:71
26-
// 签名算法名称: SHA256withRSA
27-
// 版本: 3
28-
}
29-
}
30-
31-
3216
buildTypes {
3317
release {
34-
// debuggable true
35-
minifyEnabled true
36-
shrinkResources false
18+
minifyEnabled false
3719
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
38-
signingConfig signingConfigs.release
3920
}
4021
}
4122
}

app/keystore.jks

-2.16 KB
Binary file not shown.

app/src/main/assets/ExampleApp.html

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -51,27 +51,9 @@
5151
}
5252
//--------------------
5353

54-
function scanQr() {
55-
ccapi.scanQRCode({
56-
needResult: 1, // 默认为0,扫描结果由app处理,1则直接返回扫描结果,
57-
58-
scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
59-
60-
success: function(res) {
61-
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
62-
63-
console.log("scan response: " + result);
64-
console.log("scan response: " + JSON.stringify(res));
65-
log('Native responding with ', result);
66-
}
67-
});
68-
}
69-
7054
function chooseImage() {
7155
ccapi.chooseImage({
72-
count: 1, // 默认9
73-
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
74-
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
56+
count: 1, // 数量
7557
success: function(res) {
7658
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
7759
console.log("chooseImage response: " + localIds.toString());
@@ -96,16 +78,25 @@
9678
}
9779
});
9880
}
81+
82+
83+
function jsCallNative() {
84+
window.WebViewJavascriptBridge.callHandler('abs', '{\'msg\':\'js call native test\'}', function(res) {
85+
console.log("Native response " + res);
86+
log('Native responding with ', res);
87+
});
88+
}
9989
</script>
10090
</head>
10191

10292
<body>
10393
<h1>WebViewJavascriptBridge Demo</h1>
10494
<div id='buttons'></div>
10595
<div id='log'></div>
96+
<input type="button" id="callNative" value="调用Native测试" onclick="jsCallNative()" />
10697

107-
<input type="button" id="scan" value="扫码" onclick="scanQr()" />
10898
<input type="button" id="chooseimg" value="选图" onclick="chooseImage()" />
99+
109100
<input type="button" id="deviceinfo" value="设备信息" onclick="deviceInfo()" />
110101

111102
<img src="" id="ts_img" width="100%" height="auto"/>

app/src/main/assets/js/ccnativeapi.js

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,14 @@
6161
}
6262

6363
setupWebViewJavascriptBridge(function(bridge) {
64-
bridge.registerHandler('NativeCallJS', function(data, responseCallback) {
65-
var responseData = {
66-
'Javascript Says': 'Right back atcha!'
67-
};
68-
responseCallback(responseData);
69-
});
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+
});
7072

7173
var doc = document;
7274
var readyEvent = doc.createEvent('Events');
@@ -84,13 +86,6 @@
8486
}, data.success);
8587
},
8688

87-
//扫二维码
88-
scanQRCode: function(data) {
89-
invoke("scanQRCode", {
90-
'needResult': data.needResult,
91-
'scanType': data.scanType
92-
}, data.success);
93-
},
9489
//选择图片
9590
chooseImage: function(data) {
9691
invoke("chooseImage", {

0 commit comments

Comments
 (0)