zoukankan      html  css  js  c++  java
  • android学习笔记之加载html页面及与js间的相互调用

    main中:

    <WebView 
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:id="@+id/webView"
         />

    Activity中:

    public class HtmlUIActivity extends Activity {
        private WebView webview;
        public Handler handler;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            webview = (WebView)this.findViewById(R.id.webView);
            webview.getSettings().setJavaScriptEnabled(true); //开启javascript支持
            webview.getSettings().setSupportZoom(false);
            webview.getSettings().setAppCacheEnabled(false);
            webview.getSettings().setAllowFileAccess(true);
            // java把数据传给js
            // js中可以利用“myjs”来调用show方法,myjs就相当于一个MyJavaScript对象
            // 可以调用MyJavaScript中的方法
            webview.addJavascriptInterface(new MyJavaScript(this, handler), "myjs");
            String url = "
    file:///android_asset/index.html"; // assets下的路径
            webview.loadUrl(url);    
        }
       
    }

    与js通信的类:

    public class MyJavaScript {
     private Context context;
     private WebView webview;
     private Handler handler;

     public MyJavaScript(Context context, Handler handler) {
      this.context = context;
      this.handler = handler;
      webview = (WebView)((Activity)context).findViewById(R.id.webView);
     }
     
     // 在java中调用js中的contactlist()方法,并传参数
     public void show() {
      handler.post(new Runnable() {
       
       @Override
       public void run() {
        webview.loadUrl("javascript:contactlist('" + query() + "')");
       }
      });
     }
     
     // 打电话(要加拨打权限)
     public void call(final String phone) {
      handler.post(new Runnable() {
       
       @Override
       public void run() {
        context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone)));
       }
      });
     }
     
     public String query() {
         try {
       JSONObject jsonObject = new JSONObject();
       jsonObject.put("id", 56);
       jsonObject.put("name", "胡一刀");
       jsonObject.put("phone", "151--323");
       
       JSONObject jsonObject2 = new JSONObject();
       jsonObject2.put("id", 96);
       jsonObject2.put("name", "胡勇");
       jsonObject2.put("phone", "151--326");
       JSONArray jsonArray = new JSONArray();
       jsonArray.put(jsonObject);
       jsonArray.put(jsonObject2);   
       return jsonArray.toString();
      } catch (JSONException e) {
      }
      return "";
        }
       
    }

  • 相关阅读:
    POJ 1451
    LightOJ 1224
    POJ 2001
    HDU 2072
    POJ 3764
    CH 1602
    CH 1601
    Gym 101873K
    CH 1201
    Gym 101873C
  • 原文地址:https://www.cnblogs.com/myphoebe/p/2294166.html
Copyright © 2011-2022 走看看