您的位置:首页 > 移动开发

Android中WebView的使用

2015-11-02 10:28 337 查看

Android中WebView的使用

一、什么是WebView

Android 中的WebView(网络视图),可以这么去理解,就是一个内置的浏览器。它使用了WebKit渲染引擎加载显示网页。

二、WebView的使用方式

1.实例化一个WebView

2.调用WebView的loadUrl()方法,设置WevView要显示的网页:

互联网用:webView.loadUrl("http://www.baidu.com");
本地文件用:webView.loadUrl("file:///android_asset/XX.html"); 此本地文件存放于assets 文件中

3.需要在AndroidManifest.xml文件中添加权限,否则会出现Web page not available错误。

[html] view plaincopyprint?





<uses-permission android:name="android.permission.INTERNET" />

下面是简单的示例代码:

[java] view plaincopyprint?





import android.app.Activity;

import android.os.Bundle;

import android.view.KeyEvent;

import android.webkit.WebView;

public class MainActivity extends Activity {

private WebView webview;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

//实例化WebView对象

webview = new WebView(this);

//加载需要显示的网页

webview.loadUrl("http://www.baidu.com/");

//将Web视图作为activity的视图

setContentView(webview);

}

}

4、不同的使用方法

上面的示例代码,我们讲解了直接webview视图直接作为activity的视图,在实际项目当中,我们经常是需要将webview作为一部分嵌入到activity的视图中的。如果想这么做,我们需要先在布局文件中声明WebView。
下面是示例代码:

[java] view plaincopyprint?





import android.app.Activity;

import android.os.Bundle;

import android.view.KeyEvent;

import android.webkit.WebView;

import android.webkit.WebViewClient;

public class MainActivity extends Activity {

private WebView webview;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

webview = (WebView) findViewById(R.id.webview);

//加载需要显示的网页

webview.loadUrl("http://www.baidu.com/");

}

}

xml示例代码:

[html] view plaincopyprint?





<?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>

5、webview的关闭

当我们在使用有声音播放的webview,我们如果直接finish掉webview做依赖的activity,我们会发现webview的声音播放还未停止,这是因为activity虽然被finish掉了,但是webview实际并未被销毁掉。
我们需要调用webview的destroy方法销毁webview。
下面是示例代码:

[java] view plaincopyprint?





//webview的销毁

public void stop() {

web_view.destroy();

((Activity) getContext()).finish();

}

三、webview的参数设置

webview的参数有很多,下面我们直接上一段示例代码进行说明

[java] view plaincopyprint?





//设置支持js代码

web_view.getSettings().setJavaScriptEnabled(true);

//设置支持插件

web_view.getSettings().setPluginState(PluginState.ON);

//设置允许访问文件数据

web_view.getSettings().setAllowFileAccess(true);

//设置是否支持插件

web_view.getSettings().setPluginsEnabled(true);

//支持缩放

web_view.getSettings().setSupportZoom(true);

//支持缓存

web_view.getSettings().setAppCacheEnabled(true);

//设置缓存模式

web_view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

//设置此属性,可任意比例缩放

web_view.getSettings().setUseWideViewPort(true);

web_view.getSettings().setLoadWithOverviewMode(true);

四、WebViewClient的使用

WebViewClient主要帮助WebView处理各种通知、请求事件的。比如:
onLoadResource
onPageStart
onPageFinish
onReceiveError
onReceivedHttpAuthRequest
例如以下示例代码:

[java] view plaincopyprint?





webView.setWebViewClient(new WebViewClient(){

@Override

public void onLoadResource(WebView view, String url) {

super.onLoadResource(view, url);

Log.i(TAG, "onLoadResource: ");

}

@Override

public void onPageFinished(WebView view, String url) {

super.onPageFinished(view, url);

Log.i(TAG, "onPageFinished: ");

}

@Override

public void onPageStarted(WebView view, String url, Bitmap favicon) {

super.onPageStarted(view, url, favicon);

Log.i(TAG, "onPageStarted: ");

}

@Override

public void onReceivedHttpAuthRequest(WebView view,

HttpAuthHandler handler, String host, String realm) {

super.onReceivedHttpAuthRequest(view, handler, host, realm);

Log.i(TAG, "onReceivedHttpAuthRequest: ");

}

@Override

public void onReceivedSslError(WebView view,

SslErrorHandler handler, SslError error) {

super.onReceivedSslError(view, handler, error);

Log.i(TAG, "onReceivedSslError: ");

}

@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) {

Log.i(TAG, "shouldOverrideUrlLoading: ");

return super.shouldOverrideUrlLoading(view, url);

}

@Override

public void onReceivedError(WebView view, int errorCode,

String description, String failingUrl) {

super.onReceivedError(view, errorCode, description, failingUrl);

Log.i(TAG, "onReceivedError: ");

Log.i(TAG, "errorCode: "+errorCode);

Log.i(TAG, "description: "+description);

Log.i(TAG, "failingUrl: "+failingUrl);

}

@Override

@Deprecated

public void onTooManyRedirects(WebView view, Message cancelMsg,

Message continueMsg) {

super.onTooManyRedirects(view, cancelMsg, continueMsg);

Log.i(TAG, "onTooManyRedirects");

}

});

五、WebChromeClient的使用

WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等比如
onCloseWindow(关闭WebView)
onCreateWindow()
onJsAlert (WebView上alert无效,需要定制WebChromeClient处理弹出)
onJsPrompt
onJsConfirm
onProgressChanged
onReceivedIcon
onReceivedTitle

例如以下示例代码:

[java] view plaincopyprint?





webView.setWebChromeClient(new WebChromeClient(){

@Override

public void getVisitedHistory(ValueCallback<String[]> callback) {

super.getVisitedHistory(callback);

Log.i(TAG, "getVisitedHistory");

}

@Override

public void onCloseWindow(WebView window) {

super.onCloseWindow(window);

Log.i(TAG, "onCloseWindow");

}

@Override

public boolean onCreateWindow(WebView view, boolean isDialog,

boolean isUserGesture, Message resultMsg) {

Log.i(TAG, "onCreateWindow");

return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);

}

@Override

@Deprecated

public void onExceededDatabaseQuota(String url,

String databaseIdentifier, long quota,

long estimatedDatabaseSize, long totalQuota,

QuotaUpdater quotaUpdater) {

super.onExceededDatabaseQuota(url, databaseIdentifier, quota,

estimatedDatabaseSize, totalQuota, quotaUpdater);

Log.i(TAG, "onExceededDatabaseQuota");

}

@Override

public void onProgressChanged(WebView view, int newProgress) {

super.onProgressChanged(view, newProgress);

Log.i(TAG, "onProgressChanged newProgress "+newProgress);

}

@Override

public void onReceivedIcon(WebView view, Bitmap icon) {

super.onReceivedIcon(view, icon);

Log.i(TAG, "gonReceivedIcon");

}

@Override

public void onReceivedTitle(WebView view, String title) {

super.onReceivedTitle(view, title);

Log.i(TAG, "onReceivedTitle");

}

@Override

public void onRequestFocus(WebView view) {

super.onRequestFocus(view);

Log.i(TAG, "onRequestFocus");

}

});

六、一些使用的小技巧

1、打开Android本地文件。

当网页html文件中有使用到input type=“file”的时候,Android的webview默认是不支持这个标签的,那需要怎么做呢。
这个时候需要重写webview的WebChromeClient,以下是示例代码:

[java] view plaincopyprint?





webView.setWebChromeClient(new WebChromeClient() {

public void openFileChooser(ValueCallback<Uri> uploadMsg) {

mUploadMessage = uploadMsg;

Intent i = new Intent(Intent.ACTION_GET_CONTENT);

i.addCategory(Intent.CATEGORY_OPENABLE);

i.setType("image/*");

ChangeImgActivity.this.startActivityForResult(

Intent.createChooser(i, "File Chooser"),

FILECHOOSER_RESULTCODE);

}

public void openFileChooser(ValueCallback uploadMsg,

String acceptType) {

mUploadMessage = uploadMsg;

Intent i = new Intent(Intent.ACTION_GET_CONTENT);

i.addCategory(Intent.CATEGORY_OPENABLE);

i.setType("*/*");

ChangeImgActivity.this.startActivityForResult(

Intent.createChooser(i, "File Browser"),

FILECHOOSER_RESULTCODE);

}

public void openFileChooser(ValueCallback<Uri> uploadMsg,

String acceptType, String capture) {

mUploadMessage = uploadMsg;

Intent i = new Intent(Intent.ACTION_GET_CONTENT);

i.addCategory(Intent.CATEGORY_OPENABLE);

i.setType("image/*");

ChangeImgActivity.this.startActivityForResult(

Intent.createChooser(i, "File Chooser"),

ChangeImgActivity.FILECHOOSER_RESULTCODE);

}

});

2、浏览网页的回退。

当我们在使用一些浏览器浏览网页的时候,经常会遇到这种功能,点击Android的返回键,就会产生网页回退,这个功能应该如何实现呢。
以下是示例代码:

[java] view plaincopyprint?





webView.setOnKeyListener(new View.OnKeyListener() {

@Override

public boolean onKey(View v, int keyCode, KeyEvent event) {

if (event.getAction() == KeyEvent.ACTION_DOWN) {

if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {

webView.goBack();

return true;

}

}

return false;

}

});

3、Android中Java代码和网页中js代码的交互。

在开发中,有时候需要使用Java代码去调用网页中的js代码,或者js代码要调用Java的代码。要实现此功能,首先要设置webview的参数。
Java调用js代码较为简单,直接使用loadUrl方法即可。

[java] view plaincopyprint?





flash_view.loadUrl("javascript:Play()");

js代码回调Java代码较为复杂一点。Java 代码:
//设置支持js代码

[java] view plaincopyprint?





web_view.getSettings().setJavaScriptEnabled(true);

//设置js代码的回调

web_view.addJavascriptInterface(new CallJava(), "CallJava");

//js代码的回调

private final class CallJava{

public void consoleFlashProgress(float progressSize, int total){

//设置播放进度条

showFlashProgress(progressSize, total);

}

}

JS 代码:
//动态显示播放影片的当前桢/总桢数(进度条显示)

[javascript] view plaincopyprint?





function showcount(){

total = movie.TotalFrames();

frame_number = movie.CurrentFrame();

frame_number++;

var progressSize = 500*(frame_number/total);

CallJava.consoleFlashProgress(progressSize,total/12);

}

注:一下代码很大一部分摘抄自网络,在此感谢各位代码提供者。作者只是做了整理和总结,希望能帮到各位开发者
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: