使用javascript調用android代碼
1.使用webview對象的addJavascriptInterface方法
2.addJavascriptInterface方法有兩個參數,第一個參數就是我們一般會實現一個自己的類,類里面提供我們要提供給javascript訪問的方法;第二個參數是訪問我們在obj中聲明的方法時候所用到的js對象,調用模式為window.interfaceName.方法名()或者是javascript: interfaceName.方法名() ;,如myWebView.addJavascriptInterface(new JavaScriptinterface(this), "android");
3.編寫JavaScriptinterface類,如有一個函數名為showToast()的方法
4.在html中調用時的形式:javascript:android.showToast()。
附上一個小例子:
import android.content.Context;
import android.widget.Toast;
public class JavaScriptinterface {
private Context mContext;
/** Instantiate the interface and set the context */
public JavaScriptinterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
import android.widget.Toast;
public class JavaScriptinterface {
private Context mContext;
/** Instantiate the interface and set the context */
public JavaScriptinterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private WebView myWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled( true);
myWebView.addJavascriptInterface( new JavaScriptinterface( this),
"android");
String htmlText = getFromAssets("test.html");
// 把myWebView加載html
myWebView.loadData(htmlText, "text/html", "utf-8");
myWebView.setWebViewClient( new myWebViewClient());
}
// 此按鍵監聽的是返回鍵,能夠返回到上一個網頁(通過網頁的hostlistery)
public boolean onKeyDown( int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public String getFromAssets(String fileName) {
try {
InputStreamReader inputReader = new InputStreamReader(
getResources().getAssets().open(fileName));
BufferedReader bufReader = new BufferedReader(inputReader);
String line = "";
String Result = "";
while ((line = bufReader.readLine()) != null)
Result += line;
if (bufReader != null)
bufReader.close();
if (inputReader != null)
inputReader.close();
return Result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class myWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
}
import java.io.File;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private WebView myWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled( true);
myWebView.addJavascriptInterface( new JavaScriptinterface( this),
"android");
String htmlText = getFromAssets("test.html");
// 把myWebView加載html
myWebView.loadData(htmlText, "text/html", "utf-8");
myWebView.setWebViewClient( new myWebViewClient());
}
// 此按鍵監聽的是返回鍵,能夠返回到上一個網頁(通過網頁的hostlistery)
public boolean onKeyDown( int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public String getFromAssets(String fileName) {
try {
InputStreamReader inputReader = new InputStreamReader(
getResources().getAssets().open(fileName));
BufferedReader bufReader = new BufferedReader(inputReader);
String line = "";
String Result = "";
while ((line = bufReader.readLine()) != null)
Result += line;
if (bufReader != null)
bufReader.close();
if (inputReader != null)
inputReader.close();
return Result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class myWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
}
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
< html xmlns ="http://www.w3.org/1999/xhtml" xml:lang ="zh-CN" dir ="ltr" >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" />
< script type ="text/javascript" >
function showAndroidToast(toast) {
javascript:android.showToast(toast);
}
</ script >
</ head >
< body >
< input type ="button" value ="Say hello"
onClick ="showAndroidToast('Hello Android!')" />
</ body >
</ html >
< html xmlns ="http://www.w3.org/1999/xhtml" xml:lang ="zh-CN" dir ="ltr" >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" />
< script type ="text/javascript" >
function showAndroidToast(toast) {
javascript:android.showToast(toast);
}
</ script >
</ head >
< body >
< input type ="button" value ="Say hello"
onClick ="showAndroidToast('Hello Android!')" />
</ body >
</ html >
android的應用程序中,可以直接調用WebView 中的javascript 代碼:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class MainActivity02 extends Activity {
/** Called when the activity is first created. */
private WebView webView;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
webView=(WebView) this.findViewById(R.id.webView);
button=(Button) this.findViewById(R.id.button);
WebSettings setting=webView.getSettings();
// 設置支持javascript
setting.setJavaScriptEnabled( true);
// 增加接口方法,讓html頁面調用
webView.addJavascriptInterface( new Object(){
// 這里我定義了一個撥打的方法
public void startPhone(String num){
Intent intent= new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+num));
startActivity(intent);
}
}, "demo");
// 加載頁面
webView.loadUrl("file:///android_asset/test2.html");
button.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
webView.loadUrl("javascript:show('activity傳過來的數據')"); // 調用javascript函數
/*
* 通過webView.loadUrl("javascript:xxx")方式就可以調用當前網頁中的名稱
* 為xxx的javascript方法
*/
}
});
}
import java.io.File;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class MainActivity02 extends Activity {
/** Called when the activity is first created. */
private WebView webView;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
webView=(WebView) this.findViewById(R.id.webView);
button=(Button) this.findViewById(R.id.button);
WebSettings setting=webView.getSettings();
// 設置支持javascript
setting.setJavaScriptEnabled( true);
// 增加接口方法,讓html頁面調用
webView.addJavascriptInterface( new Object(){
// 這里我定義了一個撥打的方法
public void startPhone(String num){
Intent intent= new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+num));
startActivity(intent);
}
}, "demo");
// 加載頁面
webView.loadUrl("file:///android_asset/test2.html");
button.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
webView.loadUrl("javascript:show('activity傳過來的數據')"); // 調用javascript函數
/*
* 通過webView.loadUrl("javascript:xxx")方式就可以調用當前網頁中的名稱
* 為xxx的javascript方法
*/
}
});
}
}
<!
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
>
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" >
< title >Insert title here </ title >
< script type ="text/javascript" >
function show(content){
document.getElementById("countent").innerHTML=
"這是我的javascript調用. 這是:"+content;
}
</ script >
</ head >
< body >
< table align ="center" >
< tr >< td >姓名 </ td >< td >電話 </ td ></ tr >
< tr >< td >小明 </ td >< td >< a href ="javascript:demo.startPhone(123)" >123 </ a ></ td ></ tr >
< tr >< td >小王 </ td >< td >< a href ="javascript:demo.startPhone(456)" >456 </ a ></ td ></ tr >
</ table >
< p id ="countent" >html原始數據 </ p >
</ body >
</ html >
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" >
< title >Insert title here </ title >
< script type ="text/javascript" >
function show(content){
document.getElementById("countent").innerHTML=
"這是我的javascript調用. 這是:"+content;
}
</ script >
</ head >
< body >
< table align ="center" >
< tr >< td >姓名 </ td >< td >電話 </ td ></ tr >
< tr >< td >小明 </ td >< td >< a href ="javascript:demo.startPhone(123)" >123 </ a ></ td ></ tr >
< tr >< td >小王 </ td >< td >< a href ="javascript:demo.startPhone(456)" >456 </ a ></ td ></ tr >
</ table >
< p id ="countent" >html原始數據 </ p >
</ body >
</ html >