Android中Webview使用javascript调用事先定义好的Java函数

时间:2021-07-31 17:52:38

1. 首先定义好一个类,专们用于给javascript调用

public class JavaScriptInterface {
// share your news
public void share(String newsImageUrl, String newsTitle, String newsUrl) {
Intent intent = new Intent(ActivityHomeRang.this,
ActivityShare.class);
Bundle news = new Bundle();
news.putString("ImageUrl", newsImageUrl);
news.putString("Title", newsTitle);
news.putString("Url", newsUrl);
intent.putExtras(news);
startActivity(intent);
}
}

2. 然后需要监听你的WebView, 给它加上对外的事件监听

WebView testView;
...
testView.addJavascriptInterface(new JavaScriptInterface(), "android");

3. 服务端网页的调用代码

function callAndroidShare() {
android.share('http://www.test.com', 'test title', 'http://www.test.com/news.aspx');
}