您好,登录后才能下订单哦!
android webView js 使用
1、js调用java
1、1 js代码
<script type="text/javascript">
function call(){
window.androidInterface.call('02585818031');
}
</script>
1.2、java代码
package com.example.webview;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@SuppressLint("JavascriptInterface")
public class MainActivity extends ActionBarActivity {
private WebView webView;
private int screenHeight;
private int screenWidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //设置无标题
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.web_view);
WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.addJavascriptInterface(new MyAndroidInterface(), "androidInterface");
String url ="file:///android_asset/tangbangjidian/fuwu.html";
//String url ="file:///android_asset/baitian/index.html";
webView.loadUrl(url);
}
class MyAndroidInterface{
public MyAndroidInterface(){};
@JavascriptInterface //注意:加上这行注解
public void call(String number){
//用intent启动拨打电话
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+number));
startActivity(intent);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack(); //goBack()表示返回WebView的上一页面
return false;
}
return true;
}
private class MyWebViewClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);// 当打开新链接时,使用当前的 WebView,不会使用系统其他浏览器
return true;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
2、java 调用js
2.1、java代码,webView为WebView对象
// 无参数调用
webView.loadUrl("javascript:javacalljs()");
// 传递参数调用
webView.loadUrl("javascript:javacalljswithargs(" + "'hello world'" + ")");
2.2、js代码
function javacalljs(){
document.getElementById("content").innerHTML +=
"<br\>java调用了js函数";
}
function javacalljswithargs(arg){
document.getElementById("content").innerHTML +=
("<br\>"+arg);
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。