zoukankan      html  css  js  c++  java
  • android webview 添加内置对象

    package com.android.EBrowser;

    import android.app.Activity;
    import android.graphics.Rect;
    import android.graphics.Region;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.webkit.*;

    public class EWebActivity extends Activity {
    /** Called when the activity is first created. */
    private static final String TAG = "WebActivity";
    public WebView mWeb = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      mWeb = (WebView) findViewById(R.id.webwiew);
      //此处需要打开js 开关
      mWeb.getSettings().setJavaScriptEnabled(true);
      mWeb.setBackgroundColor(0);

      ///添加java js 内置对象。
      mWeb.addJavascriptInterface(new Utility(), "Utility") ;

      mWeb.clearCache(true);
      mWeb.setInitialScale(100);
      mWeb.requestFocus();
      mWeb.loadUrl("http://172.23.65.145/index.htm");
    }



    ///* js 对象实现。
    class Utility {
      ////@JavascriptInterface 从android 4.2,之后,需要加上,否则js 运行后会找不到方法,
      ///这个需要注意。
      @JavascriptInterface
      public void setValue(String a,String b,String c,String d){
        Log.d(TAG,"====>a="+a +"b="+b+"c="+c+"d="+d);
      }

      @JavascriptInterface
      public String getValue(){
        Log.d(TAG,"====>to get value");
        return "eos";
      }
    }
    //*/
    }


    //////////////////////////////////////////////////////////////////////////////////
    //index.htm 页面实现。


    <html>
    <head>
    </head>
    <body >
    hello world
    <a id="a1" href="www.google.com" >google</a>

    </br>

    <script language="javascript">
      Utility.setValue("11","22","33","55");
      Utility.getValue();
    </script>
    </body>
    </html>

    ////////////////////////////////////////////////////////////

    (1), 关于 js 中调用内置对象 需要这样使用

        Utility.setValue(); 此种扩展的js 内置对象不能,使用new Utility().setValue();

    (2),为安全考虑,(js可以通过,反射机制去访问,修改webview 等)在android 4.2 以后。js 扩展接口需要加上,“@JavascriptInterface” ,

      否则会报 Object [object Object] has no method 这个类错误。

      

  • 相关阅读:
    python3+request接口自动化框架
    类型转换函数
    操作符重载(三)
    操作符重载(二)
    操作符重载(一)
    时间获取函数
    文件和目录
    Linux五种IO模型
    类中的函数重载
    系统调用IO和标准IO
  • 原文地址:https://www.cnblogs.com/haide/p/3533826.html
Copyright © 2011-2022 走看看