Webkit是一種開源的浏覽器引擎,蘋果Safari、Google的Chrome都是使用的Webkit內核。本文就通過實例的方式講解Android系統中Webkit的應用。
根據Google上所說,你可以在你的應用程序中調用Webkit工具,從而浏覽一個www的頁面,這一點都不假,下面來看看,原理我就不說了。大家可以看看API。
我給個簡單的上網例子給大家體驗下吧。我試驗過,可以成功的。
下面直接貼代碼:
Java代碼
- package com.gggeye.android;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.webkit.DownloadListener;
- import android.webkit.WebView;
-
- public class WebViewDemo extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- setContentView(R.layout.main);
- webView1 = new WebView(this);
- webView1
- .loadData(
- "<html><body>Can I focus?<br /><a href=\"#\">No I cannot!</a>.</body></html>",
- "text/html", "utf-8");
- this.setContentView(webView1);
- Logger.info("Download Faild _=> " + webView1.canGoBack());
- webView = new WebView(this);
- webView.loadUrl("http://www.3geye.net");
- //webView.setDownloadListener(new WebDownloadListener());
-
- new Thread(new WebDownloadListener(this)).start();
- }
- WebView webView1;
- class WebDownloadListener implements Runnable, DownloadListener {
- WebViewDemo wd;
- WebDownloadListener(WebViewDemo wd){
- this.wd = wd;
- }
- public void run() {
- int j=0;
- StringBuffer sb = new StringBuffer();
- sb.append("正在連接網絡");
- while (true) {
- try {
- Thread.sleep(4 * 1000);
- j++;
- sb.append(".");
- webView1 = new WebView(wd);
- webView1.loadData("<html><body><font color=\"red\">"
- + sb.toString() + " </font></html>", "text/html",
- "utf-8");
- Message msg = mHandler.obtainMessage();
- mHandler.sendMessage(msg);
-
- } catch (Throwable e) {
- Logger.info(e.toString());
-
- e.printStackTrace();
- }
- if (j== 3) {
- webView1 = null;
- Message msg = mHandler.obtainMessage();
- mHandler.sendMessage(msg);
- break;
- }
- }
- }
- public void onDownloadFailed(String arg0, int arg1) {
- Logger.info("Download Faild _=> " + arg0);
- }
- public void onDownloadFinished(String arg0) {
- Logger.info("Download Finished => " + arg0);
- setContentView(webView);
- }
- public void onDownloadStart(String arg0, String arg1, long arg2,
- Message arg3, Message arg4) {
- Logger.info("Download Faild _=> " + arg0);
-
- }
-
- public void onDownloadSuspended(String arg0, Message arg1) {
- Logger.info("Download Faild _=> " + arg0);
- }
- }
- Handler mHandler = new Handler(){
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- //invalidate();
- if(webView1 == null)
- setContentView(webView);
- else
- setContentView(webView1);
-
- }
- };
- WebView webView = null;
至此Android Webkit的實例就介紹完了,大家通過此代碼能夠直觀的學習到Webkit應用的知識。