標籤:
public class BoatsActivity extends Activity { Handler mHandler = new Handler();//處理訊息的handler @SuppressLint("SetJavaScriptEnabled") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setTitle("船舶查詢頁面"); final WebView mWebView = new WebView(this);//建立一個webView對象出來 將他作為activity的顯示頁面 你也可以在xml布局檔案中放入一個webView控制項在這裡初始化 setContentView(mWebView); mWebView.loadUrl("http://192.168.0.190:8080/loginDemo_gd/bots.html");//載入你要顯示的網頁 mWebView.getSettings().setJavaScriptEnabled(true);//擷取webview對象中的setting對象 設定為可以支援javascript mWebView.addJavascriptInterface(new Object() { @JavascriptInterface//sdk版本大於17要加上這句註解 訪問安全考慮 public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { Toast.makeText(BoatsActivity.this, "請輸入你要查詢的船舶", Toast.LENGTH_SHORT).show(); } }); } @JavascriptInterface public void showmsg(){ mHandler.post(new Runnable() { public void run() { Toast.makeText(BoatsActivity.this, "查詢成功", Toast.LENGTH_SHORT).show(); } }); } @JavascriptInterface public void showResult(){ mHandler.post(new Runnable() { public void run() { Toast.makeText(BoatsActivity.this, "沒有查詢到對應的資料", Toast.LENGTH_SHORT).show(); } }); } @JavascriptInterface public void alert(){ mHandler.post(new Runnable() { public void run() { Toast.makeText(BoatsActivity.this, "請輸入船舶的ID", Toast.LENGTH_SHORT).show(); } }); } }, "demo");//類的別名 js這樣調用 window.demo.方法名(js調用java方法)
//java調用js
webView.loadUrl("javascript:window.handler.show(document.getElementById(‘id‘).value,document.getElementById(‘password‘).value)");
mWebView.setWebViewClient(new WebViewClient(){ @Override public void onPageFinished(WebView view, String url) { //Toast.makeText(BoatsActivity.this, "載入完成", Toast.LENGTH_SHORT).show(); super.onPageFinished(view, url); } }); }}
android js 互調