Skip to content

Commit

Permalink
Merge pull request #3 from dtdream/develop
Browse files Browse the repository at this point in the history
refactor some code
  • Loading branch information
j1453 authored May 14, 2019
2 parents 4c0e34a + f20c7ba commit 902328f
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 82 deletions.
9 changes: 7 additions & 2 deletions library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ android {
//noinspection MinSdkTooLow
minSdkVersion 9
targetSdkVersion 28
versionCode 110
versionName "1.1.0"
versionCode 111
versionName "1.1.1"
}
buildTypes {
release {
Expand All @@ -21,6 +21,11 @@ android {
}
}

dependencies {
testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:4.2'
}

publishing {
repositories {
maven {
Expand Down
20 changes: 2 additions & 18 deletions library/src/main/java/com/github/lzyzsd/jsbridge/BridgeUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class BridgeUtil {
final static String CALLBACK_ID_FORMAT = "JAVA_CB_%s";
final static String JS_HANDLE_MESSAGE_FROM_JAVA = "javascript:WebViewJavascriptBridge._handleMessageFromNative('%s');";
final static String JS_FETCH_QUEUE_FROM_JAVA = "javascript:WebViewJavascriptBridge._fetchQueue();";
public final static String JAVASCRIPT_STR = "javascript:";

// 例子 javascript:WebViewJavascriptBridge._fetchQueue(); --> _fetchQueue
static String parseFunctionName(String jsUrl) {
Expand Down Expand Up @@ -62,28 +61,13 @@ static String getFunctionFromReturnUrl(String url) {
return null;
}


/**
* js 文件将注入为第一个script引用
*
* @param view WebView
* @param url url
*/
public static void webViewLoadJs(WebView view, String url) {
String js = "var newscript = document.createElement(\"script\");";
js += "newscript.src=\"" + url + "\";";
js += "document.scripts[0].parentNode.insertBefore(newscript,document.scripts[0]);";
view.loadUrl("javascript:" + js);
}

/**
* 这里只是加载lib包中assets中的 WebViewJavascriptBridge.js
*
* @param view webview
* @param path 路径
*/
static void webViewLoadLocalJs(WebView view, String path) {
String jsContent = assetFile2Str(view.getContext(), path);
static void loadBridgeJs(WebView view) {
String jsContent = assetFile2Str(view.getContext(), "WebViewJavascriptBridge.js");
view.loadUrl("javascript:" + jsContent);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
* Created by bruce on 10/28/15.
*/
public class BridgeWebViewClient extends WebViewClient {
private static final String BRIDGE_JS = "WebViewJavascriptBridge.js";

private long uniqueId = 0;

private Map<String, BridgeHandler> messageHandlers = new HashMap<>();
Expand All @@ -40,13 +38,12 @@ public class BridgeWebViewClient extends WebViewClient {
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
handleReturnData(url);
return true;
} else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) {
Expand All @@ -69,12 +66,12 @@ public boolean shouldOverrideUrlLoading(WebView view, String url) {
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
String url = request.getUrl().toString();
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
handleReturnData(url);
return true;
} else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) {
Expand All @@ -90,6 +87,8 @@ public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request

/**
* 获取到CallBackFunction data执行调用并且从数据集移除
* {@link #responseCallbacks}.get("_fetchQueue").onCallback
* then remove("_fetchQueue")
*
* @param url
*/
Expand All @@ -105,6 +104,7 @@ private void handleReturnData(String url) {

/**
* 刷新消息队列
* put ("_fetchQueue", callback) to {@link #responseCallbacks}
*/
private void flushMessageQueue(final WebView view) {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
Expand All @@ -124,17 +124,18 @@ public void onCallBack(String data) {
if (list == null || list.size() == 0) {
return;
}
for (int i = 0; i < list.size(); i++) {
Message m = list.get(i);
for (Message m : list) {
String responseId = m.getResponseId();
// 是否是response CallBackFunction
if (!TextUtils.isEmpty(responseId)) {
CallBackFunction function = responseCallbacks.get(responseId);
String responseData = m.getResponseData();
function.onCallBack(responseData);
responseCallbacks.remove(responseId);
if (function != null) {
function.onCallBack(responseData);
responseCallbacks.remove(responseId);
}
} else {
CallBackFunction responseFunction = null;
CallBackFunction responseFunction;
// if had callbackId 如果有回调Id
final String callbackId = m.getCallbackId();
if (!TextUtils.isEmpty(callbackId)) {
Expand All @@ -155,7 +156,6 @@ public void onCallBack(String data) {
}
};
}
// BridgeHandler执行
BridgeHandler handler = null;
if (!TextUtils.isEmpty(m.getHandlerName())) {
handler = messageHandlers.get(m.getHandlerName());
Expand Down Expand Up @@ -211,7 +211,7 @@ public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

// 加载初始化所需的 Js
BridgeUtil.webViewLoadLocalJs(view, BRIDGE_JS);
BridgeUtil.loadBridgeJs(view);

if (startupMessage != null) {
for (Message m : startupMessage) {
Expand Down
67 changes: 25 additions & 42 deletions library/src/main/java/com/github/lzyzsd/jsbridge/Message.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package com.github.lzyzsd.jsbridge;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -72,56 +69,42 @@ void setHandlerName(String handlerName) {
String toJson() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(CALLBACK_ID_STR, getCallbackId());
jsonObject.put(DATA_STR, getData());
jsonObject.put(HANDLER_NAME_STR, getHandlerName());
String data = getResponseData();
if (TextUtils.isEmpty(data)) {
jsonObject.put(RESPONSE_DATA_STR, data);
} else {
jsonObject.put(RESPONSE_DATA_STR, new JSONTokener(data).nextValue());
}
jsonObject.put(RESPONSE_DATA_STR, getResponseData());
jsonObject.put(RESPONSE_ID_STR, getResponseId());
jsonObject.put(CALLBACK_ID_STR, callbackId);
jsonObject.put(DATA_STR, data);
jsonObject.put(HANDLER_NAME_STR, handlerName);
jsonObject.put(RESPONSE_DATA_STR, responseData);
jsonObject.put(RESPONSE_ID_STR, responseId);
return jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

public static Message toObject(String jsonStr) {
static Message formJson(String jsonStr) throws JSONException {
Message m = new Message();
try {
JSONObject jsonObject = new JSONObject(jsonStr);
m.setHandlerName(jsonObject.has(HANDLER_NAME_STR) ? jsonObject.getString(HANDLER_NAME_STR) : null);
m.setCallbackId(jsonObject.has(CALLBACK_ID_STR) ? jsonObject.getString(CALLBACK_ID_STR) : null);
m.setResponseData(jsonObject.has(RESPONSE_DATA_STR) ? jsonObject.getString(RESPONSE_DATA_STR) : null);
m.setResponseId(jsonObject.has(RESPONSE_ID_STR) ? jsonObject.getString(RESPONSE_ID_STR) : null);
m.setData(jsonObject.has(DATA_STR) ? jsonObject.getString(DATA_STR) : null);
return m;
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonObject = new JSONObject(jsonStr);
m.setHandlerName(jsonObject.optString(HANDLER_NAME_STR, null));
m.setCallbackId(jsonObject.optString(CALLBACK_ID_STR, null));
m.setResponseData(jsonObject.optString(RESPONSE_DATA_STR, null));
m.setResponseId(jsonObject.optString(RESPONSE_ID_STR, null));
m.setData(jsonObject.optString(DATA_STR, null));
return m;
}

public static List<Message> toArrayList(String jsonStr) {
List<Message> list = new ArrayList<Message>();
try {
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
Message m = new Message();
JSONObject jsonObject = jsonArray.getJSONObject(i);
m.setHandlerName(jsonObject.has(HANDLER_NAME_STR) ? jsonObject.getString(HANDLER_NAME_STR) : null);
m.setCallbackId(jsonObject.has(CALLBACK_ID_STR) ? jsonObject.getString(CALLBACK_ID_STR) : null);
m.setResponseData(jsonObject.has(RESPONSE_DATA_STR) ? jsonObject.getString(RESPONSE_DATA_STR) : null);
m.setResponseId(jsonObject.has(RESPONSE_ID_STR) ? jsonObject.getString(RESPONSE_ID_STR) : null);
m.setData(jsonObject.has(DATA_STR) ? jsonObject.getString(DATA_STR) : null);
list.add(m);
}
} catch (JSONException e) {
e.printStackTrace();
/**
* 按照最初的做法是不处理异常的,在 BridgeWebViewClient#flushMessageQueue(WebView) 中捕获异常
*
* @param jsonStr
* @return
* @throws JSONException
*/
static List<Message> toArrayList(String jsonStr) throws JSONException {
List<Message> list = new ArrayList<>();
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
list.add(Message.formJson(jsonObject.toString()));
}
return list;
}
Expand Down
63 changes: 63 additions & 0 deletions library/src/test/java/com/github/lzyzsd/jsbridge/MessageTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.github.lzyzsd.jsbridge;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

@RunWith(RobolectricTestRunner.class)
public class MessageTest {

@Test
public void empty_toJson() {
Message m = new Message();
assertEquals("{}", m.toJson());
}

@Test
public void noResponseData_toJson() {
Message m = new Message();
m.setData("empty");
m.setCallbackId("callbackId11");
m.setHandlerName("testToJson");
m.setResponseId("responseIdAA");
String excepted = "{\"data\":\"empty\",\"callbackId\":\"callbackId11\",\"handlerName\":\"testToJson\",\"responseId\":\"responseIdAA\"}";
assertEquals(excepted, m.toJson());
}

@Test
public void hasSimpleResponseData_toJson() {
Message m = new Message();
m.setResponseData("simple Str");
String excepted = "{\"responseData\":\"simple Str\"}";
assertEquals(excepted, m.toJson());
}

@Test
public void noResponseData_formJson() throws Exception {
String sample = "{\"data\":\"empty\",\"callbackId\":\"callbackId11\",\"handlerName\":\"testToJson\",\"responseId\":\"responseIdAA\"}";
Message m = Message.formJson(sample);
assertEquals("empty", m.getData());
assertEquals("callbackId11", m.getCallbackId());
assertEquals("testToJson", m.getHandlerName());
assertEquals("responseIdAA", m.getResponseId());
assertNull(m.getResponseData());
}

@Test
public void toArrayList() throws Exception {
String sample = "[{\"data\":\"empty\",\"callbackId\":\"callbackId11\",\"handlerName\":\"testToJson\",\"responseId\":\"responseIdAA\"},{\"data\":\"empty2\",\"callbackId\":\"callbackId22\",\"handlerName\":\"testToJson\",\"responseId\":\"responseIdBB\"}]";
List<Message> result = Message.toArrayList(sample);
assertEquals(2, result.size());
assertEquals("callbackId11", result.get(0).getCallbackId());
assertEquals("empty", result.get(0).getData());
assertEquals("responseIdAA", result.get(0).getResponseId());
assertEquals("callbackId22", result.get(1).getCallbackId());
assertEquals("empty2", result.get(1).getData());
assertEquals("responseIdBB", result.get(1).getResponseId());
}
}

0 comments on commit 902328f

Please sign in to comment.