Android之如何使用javascript調用android代碼

來源:互聯網
上載者:User

使用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 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;
        }

    }
}

<!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>

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方法
                  */
              } 
          }); 
}

}  

<!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>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.