In java

// 进入prompt回调
public class JSBridgeWebChromeClient extends WebChromeClient {
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
result.confirm(JSBridge.callJava(view, message));
return true;
}
}

// 调用java逻辑
public class JSBridge {
...
public static String callJava(WebView webView, String uriString) {
String methodName = "";
String className = "";
String param = "{}";
String port = "";
if (!TextUtils.isEmpty(uriString) && uriString.startsWith("JSBridge")) {
Uri uri = Uri.parse(uriString);
className = uri.getHost();
param = uri.getQuery();
port = uri.getPort() + "";
String path = uri.getPath();
if (!TextUtils.isEmpty(path)) {
methodName = path.replace("/", "");
}
}

// 基于上面的className、methodName和port path调用对应类的方法
if (exposedMethods.containsKey(className)) {
HashMap<String, Method> methodHashMap = exposedMethods.get(className);

if (methodHashMap != null && methodHashMap.size() != 0 && methodHashMap.containsKey(methodName)) {
Method method = methodHashMap.get(methodName);
if (method != null) {
try {
method.invoke(null, webView, new JSONObject(param), new Callback(webView, port));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Return null;
}
}

// showToast function implemented directly into
public static void showToast (the WebView the webView, the JSONObject param, the Callback Final the callback) {
String Message = param.optString ( "MSG");
Toast.makeText (the webView. the getContext (), Message, Toast.LENGTH_SHORT) the .Show ();
IF (the callback = null) {!
the try {
the JSONObject the JSONObject new new = Object ();
object.put ( "Key", "value");
object.put ( "key1", "VALUE1");
callback.apply (getJSONObject (0, "OK", Object));
} the catch (Exception E) {
e.printStackTrace ();
}
}
}

// callback.apply method as a program implemented as follows: that is, through webView.js implemented loadUrl java method calls the
public class Callback {
private static Handler mHandler = new Handler(Looper.getMainLooper());
private static final String CALLBACK_JS_FORMAT = "javascript:JSBridge.onFinish('%s', %s);";
private String mPort;
private WeakReference<WebView> mWebViewRef;

public Callback(WebView view, String port) {
mWebViewRef = new WeakReference<>(view);
mPort = port;
}

public void apply(JSONObject jsonObject) {
final String execJs = String.format(CALLBACK_JS_FORMAT, mPort, String.valueOf(jsonObject));
if (mWebViewRef != null && mWebViewRef.get() != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
mWebViewRef.get().loadUrl(execJs);
}
});

}

}

 

Guess you like

Origin www.cnblogs.com/ly570/p/11291185.html