在您的Android App工程的Activity文件中,导入WebView组件的依赖库。import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
在AndroidManifest.xml配置文件中,设置网页加载的权限。
说明:如果存在其它HTTP资源调用,也需要增加相应的配置。
...
android:usesCleartextTraffic="true"
...>
在activity_main.xml布局文件中,添加WebView组件。
android:layout_height="match_parent"
android:layout_width="match_parent" />
在Activity文件中,加载HTML5业务页面。public class MainActivity extends AppCompatActivity {
private WebView testWebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
// 页面布局。
testWebview = (WebView) findViewById(R.id.webview);
// 设置屏幕自适应。
testWebview.getSettings().setUseWideViewPort(true);
testWebview.getSettings().setLoadWithOverviewMode(true);
// 建议禁止缓存加载,以确保在攻击发生时可快速获取最新的滑动验证组件进行对抗。
testWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
// 设置不使用默认浏览器,而直接使用WebView组件加载页面。
testWebview.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// 设置WebView组件支持加载JavaScript。
testWebview.getSettings().setJavaScriptEnabled(true);
// 建立JavaScript调用Java接口的桥梁。
testWebview.addJavascriptInterface(new testJsInterface(), "testInterface");
// 加载业务页面。
testWebview.loadUrl("http://39.x.x.x/demo/");
}
}
在Activity文件中,添加自定义Java接口(testJsInterface),并定义getSlideData方法获取滑块数据。import android.webkit.JavascriptInterface;
public class testJsInterface {
@JavascriptInterface
public void getSlideData(String callData) {
System.out.println(callData);
}
}
在Activity的initView()方法中,将所添加的自定义Java接口与JavaScript函数绑定。// 设置WebView组件支持JavaScript。
testWebview.getSettings().setJavaScriptEnabled(true);
// 建立JavaScript调用Java接口的桥梁。
testWebview.addJavascriptInterface(new testJsInterface(), "testInterface");