AgentWeb中如果想使用JsBridge,可以参考这个demo。JsbridgeWebFragment
自己在项目中仿着这个demo使用的时候,代码如下。
mBridgeWebView = new BridgeWebView(getActivity());
mAgentWeb = AgentWeb.with(this)//
.setAgentWebParent(mFrameLayout, -1, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))//传入AgentWeb的父控件。
.useDefaultIndicator(-1, 3)//设置进度条颜色与高度,-1为默认值,高度为2,单位为dp。
.setAgentWebWebSettings(getSettings())//设置 IAgentWebSettings。
.setWebViewClient(getWebViewClient())//WebViewClient , 与 WebView 使用一致 ,但是请勿获取WebView调用setWebViewClient(xx)方法了,会覆盖AgentWeb DefaultWebClient,同时相应的中间件也会失效。
.setWebChromeClient(new WebChromeClient()) //WebChromeClient
.setPermissionInterceptor(mPermissionInterceptor) //权限拦截 2.0.0 加入。
.setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //严格模式 Android 4.2.2 以下会放弃注入对象 ,使用AgentWebView没影响。
.setMainFrameErrorView(R.layout.agentweb_error_page, -1) //参数1是错误显示的布局,参数2点击刷新控件ID -1表示点击整个布局都刷新, AgentWeb 3.0.0 加入。
.useMiddlewareWebChrome(mMiddlewareWebChromeBase) //设置WebChromeClient中间件,支持多个WebChromeClient,AgentWeb 3.0.0 加入。
.useMiddlewareWebClient(mMiddlewareWebClientBase) //设置WebViewClient中间件,支持多个WebViewClient, AgentWeb 3.0.0 加入。
.setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)//打开其他页面时,弹窗质询用户前往其他应用 AgentWeb 3.0.0 加入。
.interceptUnkownUrl() //拦截找不到相关页面的Url AgentWeb 3.0.0 加入。
.setWebView(mBridgeWebView)
.createAgentWeb()//创建AgentWeb。
.ready()//设置 WebSettings。
.go(url);
在安卓6.0的机器上试了一下,发现一切正常。结果后来发现,安卓9.0以上的机器(不确定其他版本),在Js中无法正常调用安卓里的方法。。经过测试,发现初始化AgentWeb时,去掉.interceptUnkownUrl()
,Js即可正常调用安卓中的方法。