android JS相互呼出
26697 ワード
public class SystemWebView extends Activity { Button button;
WebView webView ;
WebSettings webSetting;
@JavascriptInterface
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_system_webview);
button = (Button)findViewById(R.id.button);
webView = (WebView)findViewById(R.id.webView);
//
webView.loadUrl("file:///android_asset/hello.html");
WebSettings settings = webView.getSettings();
settings.setDefaultTextEncodingName("GBK");//
settings.setJavaScriptEnabled(true); // JS
// js window , js android , JsCallAndroid
webView.addJavascriptInterface(new JSCallAndroid(), "JsCallAndroid");
// WebView , WebView
webView.setWebViewClient(new WebViewClient() { @Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub // , true WebView , false view.loadUrl(url);
return true;
} });
webView.setWebChromeClient(new WebChromeClient() { @Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) { // TODO Auto-generated method stub return super.onJsAlert(view, url, message, result);
} });
button.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View view) { webView.loadUrl("javascript: showFromHtml2('android said:')");
} });
} class JSCallAndroid{ @JavascriptInterface
public void htmlCallAndroid(){ Uri smsToUri = Uri.parse("smsto:");
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("sms_body", " ");
startActivity(intent);
} @JavascriptInterface
public String htmlCallAndroid2(final String str){ Gson gson = new Gson();
JSONObject jsonObject = null;
try { jsonObject = new JSONObject(str);
String name = jsonObject.getString("name");
String password = jsonObject.getString("password");
return "{\"name\":" + name + " turn," + "\"password\":"+ password + " turn}";
} catch (JSONException e) { e.printStackTrace();
} return null;
} } }
html
<!doctype html>
<html lang="en">
<head>
<meta charset="GBK">
<title>Document</title>
<script>
function showFromHtml2(param){
alert(param + " ");
}
function subInput(){
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
var str = '{"name":"' + name + '","password":"' + password +'"}';
// android
var str2 = window.JsCallAndroid.htmlCallAndroid2(str);
alert(str2);
}
function sendMsg(){
// android
window.JsCallAndroid.htmlCallAndroid();
}
</script>
</head>
<body>
<form>
:<input id="name" type="email" name="email"/>
<br/>
: <input id="password" type="text" name="password"/>
</br>
<input type="submit" value=" " onclick="subInput()"/>
<input type="button" value=" " onclick="sendMsg()"/>
</form>
</body>
</html>