android學習筆記之載入html頁面及與js間的相互調用

來源:互聯網
上載者:User

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 "";
    }
   
}

相關文章

聯繫我們

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