您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。