【Js】調用Android WebView定義的方法總結

來源:互聯網
上載者:User

標籤:android   http   java   資料   os   cti   

先貼代碼:

package com.example.demowebview;

import Android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.webkit.JAVAscriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends Activity {
WebView webView;
Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);

webView = new WebView(this);
setContentView(webView);

WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://192.168.0.108:8083/");

class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
return true;
}
}
webView.setWebChromeClient(new MyWebChromeClient());

final int UserID = 1001;

class JsInterFace{
@JavascriptInterface
public int GetUserID(){
return UserID;
}
}
webView.addJavascriptInterface(new JsInterFace(), "AndroidJs");

}

}

這裡定義了一個GetUserID方法供http://192.168.0.108:8083/頁面調用。
但是要注意不能在public int GetUserID()前面漏寫這句:@JavascriptInterface
Web端的http://192.168.0.108:8083/頁面只需按window.AndroidJs.GetUserID()方式調用即可。
:Web端通過調用Android端的GetUserID()方法擷取到資料,然後Alert()這個值。

 

打個廣告:需要iPhone 5s / 5c / 5 鋼化玻璃膜、保護套/保護殼的朋友,上http://kener.taobao.com,聯絡客服給同行的程式員們一個優惠的價格哦!

轉自:http://www.dengyukeji.com/thread-562-1-1.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.