初始化WebView并且加载网络页面
- 加载assets目录下的文件
webView.loadUrl("file:///android_asset/JavaAndJavaScriptCall.html");
网页调用APP端方法
//android为统一标识 call方法为Android客户端的拨打电话方法
window.android.call("18217057136");
private void initWebView() {
webView = new WebView(this);
WebSettings webSettings = webView.getSettings();
//设置支持javaScript脚步语言
webSettings.setJavaScriptEnabled(true);
//支持双击-前提是页面要支持才显示
webSettings.setUseWideViewPort(true);
//支持缩放按钮-前提是页面要支持才显示
webSettings.setBuiltInZoomControls(true);
//设置客户端-不跳转到默认浏览器中
webView.setWebViewClient(new WebViewClient());
//加载网络资源
webView.loadUrl("http://atguigu.com/teacher.shtml");
// webView.loadUrl("file:///android_asset/JavaAndJavaScriptCall.html");
//显示页面
setContentView(webView);
}
- Java调用javaScript
/**
* Java调用javaScript
* @param numebr
*/
private void login(String numebr) {
webView.loadUrl("javascript:javaCallJs("+"'"+numebr+"'"+")");
setContentView(webView);
}
- JavaScript调java
- 1_配置Javascript接口
//设置支持js调用java
webView.addJavascriptInterface(new AndroidAndJSInterface(),"Android");
- 实现Javascript接口类
/**
* js可以调用该类的方法
*/
class AndroidAndJSInterface{
public void showToast(){
Toast.makeText(JavaAndJSActivity.this, "我被js调用了", Toast.LENGTH_SHORT).show();
}
}
- 解决该WebView.addJavascriptInterface接口不起作用的两种办法
针对版本改成16
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.atguigu.androidandh5"
minSdkVersion 14
targetSdkVersion 16
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
}
在JavaScript接口类的方法加上@JavascriptInterface注解
/**
* js可以调用该类的方法
*/
class AndroidAndJSInterface{
@JavascriptInterface
public void showToast(){
Toast.makeText(JavaAndJSActivity.this, "我被js调用了", Toast.LENGTH_SHORT).show();
}
}
- 配置Javascript接口
//设置支持js调用java
webView.addJavascriptInterface(new AndroidAndJSInterface(),"android");
- 拨打电话的代码
public void call(String phone) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
// startActivity(intent);
}