Android端代码
package com.gta.gj.webview;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import com.gta.gj.webview.download.WebDownloadListener;
import com.gta.gj.webview.settings.WebViewDefaultSettings;
import com.gta.gj.webview.webchromeclient.CustomWebChromeClient;
import com.gta.gj.webview.webviewclient.CustomWebViewClient;
import com.gta.gj.webview.webviewclient.WebViewCallBack;
public class BaseWebView extends WebView {
public static final String TAG = "BaseWebView";
private boolean mNoCache = true;
private CustomWebChromeClient mCustomWebChromeClient;
public BaseWebView(Context context) {
super(context);
init();
}
public BaseWebView(Context context, boolean noCache) {
super(context);
mNoCache = noCache;
init();
}
public BaseWebView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
public void init() {
addJavascriptInterface(this, "app");
WebViewDefaultSettings.getInstance().setSettings(this, mNoCache);
}
public void registerWebViewCallBack(WebViewCallBack webViewCallBack) {
setWebViewClient(new CustomWebViewClient(webViewCallBack));
mCustomWebChromeClient = new CustomWebChromeClient(webViewCallBack);
setWebChromeClient(mCustomWebChromeClient);
setDownloadListener(new WebDownloadListener(getContext()));
}
public CustomWebChromeClient getWebChromeClient() {
return mCustomWebChromeClient;
}
@JavascriptInterface
public void fromHtml(final String jsParam) {
Log.e(TAG, "this is a call from html javascript." + jsParam);
if (!TextUtils.isEmpty(jsParam)) {
WebViewJavascriptDispatcher.getInstance().executeCommand(jsParam);
}
}
public void handleCallback(final String callbackName, final String response) {
if (!TextUtils.isEmpty(callbackName) && !TextUtils.isEmpty(response)) {
post(new Runnable() {
@Override
public void run() {
String jscode = "javascript:xiangxuejs.callback('" + callbackName + "'," + response + ")";
evaluateJavascript(jscode, null);
}
});
}
}
}
在 webview_flutter_android --> JavaScriptChannel.jave 添加下面代码
// Suppressing unused warning as this is invoked from JavaScript.
@SuppressWarnings("unused")
@JavascriptInterface
public void fromHtml(final String message) {
final Runnable postMessageRunnable =
() -> {
flutterApi.postMessage(JavaScriptChannel.this, message, reply -> {});
};
if (platformThreadHandler.getLooper() == Looper.myLooper()) {
postMessageRunnable.run();
} else {
platformThreadHandler.post(postMessageRunnable);
}
}
网友评论