Android学习13-----网络通信(4) WebView组件

WebView 是一个开发的浏览器组件,是基于 WebKit 内核开发出来的,如 Safari Google Chrome 浏览器都是通过 WebView 实现的,而在 Android 系统中,默认提供了 WebView 组件的支持。除了支持各个浏览器的“前进”、“后退”等功能之外,最为强大的是在 WebView 组件之中也支持 JavaScript 的操作。

一、加载网页

要想使用 WebView 加载网页,最简单的方法就是使用 loadUrl() 方法,此方法只需要输入网页的 URL 地址即可。下面涉及网络访问的需要加载网络访问权限,这里不一一说了。

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" 
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<LinearLayout 
		xmlns:android="http://schemas.android.com/apk/res/android"
		android:orientation="horizontal" 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
		<Button
			android:id="@+id/open"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content" 
			android:text="打开" />
		<EditText
			android:id="@+id/inputurl"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content" 
			android:text="http://www.baidu.com" />
	</LinearLayout>
	<WebView
		android:id="@+id/webview"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"  />
</LinearLayout>

WebView01_Activity.java

package com.iflytek.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class WebView01_Activity extends Activity {
	private Button openBtn = null;
	private EditText inputurl = null;
	private WebView webview = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.openBtn = (Button) super.findViewById(R.id.open);
		this.inputurl = (EditText) super.findViewById(R.id.inputurl);
		this.webview = (WebView) super.findViewById(R.id.webview);
		this.openBtn.setOnClickListener(new OpenOnClickListenerImpl());
	}

	private class OpenOnClickListenerImpl implements OnClickListener {

		@Override
		public void onClick(View v) {
			String url = WebView01_Activity.this.inputurl.getText().toString();
			WebView01_Activity.this.webview.loadUrl(url);// 加载页面
		}

	}
}

上面也可以将字符串中定义的HTML标记变为网页,在WebView中显示。
Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" 
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<WebView
		android:id="@+id/webview"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"  /> 
</LinearLayout>

WebView02_Activity.java

package com.iflytek.demo;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebView02_Activity extends Activity {

	private WebView webview = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.webview = (WebView) super.findViewById(R.id.webview);
		String data = "<h1>this.is baidu.</h1>"
				+ "<h2><a href=\"http://www.baidu.com\">BAIDU</a><h2>";
		this.webview.loadData(data, "text/html", "UTF-8");
	}
}

二、控制 WebView ,实现属于自己的浏览器

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/open"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="打开" />

        <Button
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="后退" />

        <Button
            android:id="@+id/forward"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="前进" />

        <Button
            android:id="@+id/zoomout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="缩小" />

        <Button
            android:id="@+id/zoomin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="放大" />

        <Button
            android:id="@+id/clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="清空" />
    </LinearLayout>

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

</LinearLayout>

WebView02_Activity.java

package com.iflytek.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;

public class WebView02_Activity extends Activity {
	private Button openBtn = null;
	private Button backBtn = null;
	private Button forwardBtn = null;
	private Button zoominBtn = null;
	private Button zoomoutBtn = null;
	private Button clearBtn = null;
	private WebView webview = null;
	private String urlData[] = new String[] { "http://www.baidu.com",
			"http://www.iteye.com", "http://www.eoeandroid.com/",
			"http://blog.jobbole.com/", "http://www.cnblogs.com/" };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.webview = (WebView) super.findViewById(R.id.webview);
		this.openBtn = (Button) super.findViewById(R.id.open);
		this.backBtn = (Button) super.findViewById(R.id.back);
		this.forwardBtn = (Button) super.findViewById(R.id.forward);
		this.zoominBtn = (Button) super.findViewById(R.id.zoomin);
		this.zoomoutBtn = (Button) super.findViewById(R.id.zoomout);
		this.clearBtn = (Button) super.findViewById(R.id.clear);

		this.openBtn.setOnClickListener(new OpenOnClickListenerImpl());
		this.backBtn.setOnClickListener(new BackOnClickListenerImpl());
		this.forwardBtn.setOnClickListener(new ForwardOnClickListenerImpl());
		this.zoominBtn.setOnClickListener(new ZoomInOnClickListenerImpl());
		this.zoomoutBtn.setOnClickListener(new ZoomOutClickListenerImpl());
		this.clearBtn.setOnClickListener(new ClearOnClickListenerImpl());
	}

	private class OpenOnClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			WebView02_Activity.this.showUrlDialog();
		}
	}

	private class BackOnClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (WebView02_Activity.this.webview.canGoBack()) {
				WebView02_Activity.this.webview.goBack();
			}
		}
	}

	private class ForwardOnClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (WebView02_Activity.this.webview.canGoForward()) {
				WebView02_Activity.this.webview.goForward();
			}
		}
	}

	private class ZoomInOnClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			WebView02_Activity.this.webview.zoomIn();
		}
	}

	private class ZoomOutClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			WebView02_Activity.this.webview.zoomOut();
		}
	}

	private class ClearOnClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			WebView02_Activity.this.webview.clearHistory();
		}
	}

	private void showUrlDialog() {
		Dialog dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher)
				.setTitle("请选择要浏览的网站")
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				})
				.setItems(this.urlData, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						webview.loadUrl(urlData[which]);
					}
				}).create();
		dialog.show();
	}
}

三、通过 HTML 定义显示界面

在前面我们使用 WebView 组件浏览的是 Web 站点,而实际上,也可以通过 WebView 组件加载项目中的 HTML 页面,以达到界面显示的操作,但是在进行这些操作之前,首先必须了解 android.webkit.WebSettings 类,此类的主要功能是进行 WebView 的操作设置,用户可以通过 WebView 类中的 getSettings() 方法取得 WebSettings 类的对象,该对象常用方法如下:

No.

方法

描述

1

Public void setBuitInZoomControls(Boolean enabled)

设置是否可以进行缩放控制

2

Public synchronized void setJavaScriptEnabled(Boolean falg)

设置是否启动 JavaScript 支持

3

Public void setSaveFormData(Boolean save)

设置是否保存表单数据

4

Public void setSavePassword(Boolean save)

设置是否保存密码

5

Public synchronized void setGeolocationEnabled(Boolean flag)

设置是否可以获取地理位置

要通过 HTML 设置显示界面,则还涉及 HTML 文件的保存问题,此时用户可以将文件保存在 Android 项目的 assets 文件夹下的 html 文件夹。

下面定义包含 JS HTML 文件 assests/html/show_htmlinjs.html

<!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 language="javascript">
	function openurl(url) {
		window.location = url;
	}
</script>
</head>
<body>
	<center>
		<img src="../images/java.jpg" width="150" height="220">
		<h3>请选择您要浏览的网站:</h3>
		<select name="url" onchange="openurl(this.value)">
			<option value="http://www.baidu.com">BaiDu</option>
			<option value="http://www.iteye.com">Iteye</option>
			<option value="http://www.google.com">Googlg</option>
		</select>
	</center>
</body>
</html>

WebView03_Activity.java

package com.iflytek.demo;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebView03_Activity extends Activity {
	private WebView webview = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    	this.webview = (WebView) super.findViewById(R.id.webview);
		this.webview.getSettings().setJavaScriptEnabled(true); // 启用JavaScript
		this.webview.getSettings().setBuiltInZoomControls(true); // 控制页面缩放
		this.webview.loadUrl("file:/android_asset/html/show_htmlinjs.html");
    }
}

四、本地程序与 JavaScript 互操作

使用 WebView 还可以专门处理 JavaScript 返回的警告框、确认框等互操作,此时就需要使用 android.webkit.WebChromeClient 客户端处理的操作类完成。其常用方法:

No.

方法

描述

1

Public void onCloseWindow(WebView window)

窗口关闭操作

2

Public Boolean onCreateWindow(WebView view,Boolean dialog,Boolean userGesture,Message resultMsg)

创建新的 WebView

3

Public Boolean onJsAlert(WebView view String url,String message,JsResult result)

弹出警告框互操作

4

Public Boolean onJsBeforeUnload(WebView view,String url,String message,JsResult result)

页面关闭互操作

5

Public Boolean onJsConfirm(WebView view,String url,String message,JsResult result)

弹出确认框互操作

6

Public Boolean onJsPrompt(WebView view,String url,String message,String defaultValue,JsPromptResult result)

弹出提示框互操作

7

Public Boolean onJsTimeout()

计时器已到互操作

8

Public void onProgressChanged(WebView view,int newProgress)

进度改变互操作

9

Public void onReceivedTitle(WebView view,String title)

接收页面标题互操作

定义 HTML 界面 show_js.html

<head>
	<title>Iteye:www.iteye.com</title>
	<meta http-equiv="Content-Type" content="text/html;charset=GBK">
	<script language="javascript">
		function openAlert(){
			window.alert("Iteye:\nwww.iteye.com") ;
		}
		function openConfirm(){
			if (window.confirm("是否删除此信息?")) {
				window.location = "delete_js.html" ;
			}
		}
	</script>
</head>
<input type="button" value="弹出警告框" onclick="openAlert()">
<input type="button" value="弹出确认框" onclick="openConfirm()">

delete_js.html

<head>
	<title>Iteye:www.iteye.com</title>
	<meta http-equiv="Content-Type" content="text/html;charset=GBK">
</head>
<h1>信息已删除!</h1>

WebView04_Activity.java

package com.iflytek.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

public class WebView04_Activity extends Activity {
	private WebView webview = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.webview = (WebView) super.findViewById(R.id.webview);
		this.webview.getSettings().setJavaScriptEnabled(true); // 启用JavaScript
		this.webview.getSettings().setBuiltInZoomControls(true); // 控制页面缩放
		this.webview.setWebChromeClient(new WebChromeClientImpl());//接受客户端操作
		this.webview.loadUrl("file:/android_asset/html/show_js.html");//读取网页
	}

	private class WebChromeClientImpl extends WebChromeClient {

		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				final JsResult result) {
			Dialog dialog = new AlertDialog.Builder(WebView04_Activity.this)
					.setIcon(R.drawable.ic_launcher)
					.setTitle("Xdwang警告")
					.setMessage(message)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Toast.makeText(WebView04_Activity.this,
											"关闭警告框", Toast.LENGTH_SHORT).show();
									result.cancel();
								}
							}).create();
			dialog.show();
			return true;
		}

		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				final JsResult result) {
			Dialog dialog = new AlertDialog.Builder(WebView04_Activity.this)
					.setIcon(R.drawable.ic_launcher)
					.setTitle("确定删除?")
					.setMessage(message)
					.setPositiveButton("删除",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Toast.makeText(WebView04_Activity.this,
											"确定删除", Toast.LENGTH_SHORT).show();
									result.confirm();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Toast.makeText(WebView04_Activity.this,
											"取消删除", Toast.LENGTH_SHORT).show();
									result.cancel();
								}
							}).create();
			dialog.show();
			return true;
		}

		@Override
		public void onReceivedTitle(WebView view, String title) {
			WebView04_Activity.this.setTitle(title);
			super.onReceivedTitle(view, title);
		}

	}
}

五、使用 JavaScript 调用 Android

前面我们说了如何通过 Android 调用 JavaScript 的操作,反过来, JavaScript 程序也可以调用 Android 成词,此时就必须依靠 WebView 中的 addJavaScriptInterface() 方法完成,定义如下:

Public void addJavaScriptInterface(Object 操作对象 ,String 标记名称 )

在此方法中,用户需要一个标记的名称,而该标记名称的主要功能就是绑定 HTML android 间的联络标记

WebView05_Activity.java

package com.iflytek.demo;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebView05_Activity extends Activity {
	private WebView webview = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.webview = (WebView) super.findViewById(R.id.webview);
		this.webview.getSettings().setJavaScriptEnabled(true); // 启用JavaScript
		this.webview.getSettings().setBuiltInZoomControls(true); // 控制页面缩放
		this.webview.addJavascriptInterface(this, "xdwangandroid");
		this.webview.loadUrl("file:/android_asset/html/show_js.html");
	}

	public String getContent() {
		return "ITEYE:www.iteye.com";
	}
}

show_js.html

<head>
<title>Iteye:www.iteye.com</title>
<meta http-equiv="Content-Type" content="text/html ; charset=GBK">
</head>
<h1>
	<span id="msg">等待接收信息...</span>
</h1>
<script language="javascript">
	document.getElementById("msg").innerHTML = window.xdwangandroid.getContent();
</script>

猜你喜欢

转载自xdwangiflytek.iteye.com/blog/1728653