主要是在androidactivity中调用addJavascriptInterface (phone, "androidPhoneObject"); 给javascript提供一个接口;让javascript来调用此接口实现javascript调android;此处用javascript调用android拨打电话;
具体代码实现如下;
java 代码;
package com.tarena.webview;
import android.net.Uri;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
@SuppressLint("JavascriptInterface")
public class MainActivity extends Activity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
webView=(WebView) findViewById(R.id.webView1);
//用系统的浏览器打开网页,解决
webView.setWebViewClient(new WebViewClient());
//网站有两种
//1,www.sohu.com给电脑看,1024*768
//2,wap.sohu.com,http:wap.baidu.com给手机看
//要求这个网页能适应不同的屏幕,实现用div+css
//服务器:jsp,servlet,jdbc
//客户端:html,css,javaScript
//webView.loadUrl("http://wap.sohu.com");
//webView.loadUrl("http://192.168.188.98:8080/tarenaEnglish/index.jsp");
webView.loadUrl("file:///android_asset/test.html");
WebSettings settings=webView.getSettings();
//执行javaScript
settings.setJavaScriptEnabled(true);
Button btn1=(Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
webView.loadUrl("javascript:changeUsername()");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Phone phone=new Phone();
//phone.call("");
//把phone对象的功能公开给javaScript
webView.
addJavascriptInterface
(phone, "androidPhoneObject");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
final class Phone
{
public void call(String mobile)
{
try {
Intent intent=new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+mobile));
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
本文介绍如何在Android应用中使用WebView加载本地HTML文件,并通过addJavascriptInterface方法实现JavaScript与原生Android代码之间的通信,以完成拨打电话等功能。
4669

被折叠的 条评论
为什么被折叠?



