android开发步步为营之44:使用WebView打开web页面

来源:互联网 发布:ubuntu安装旧版本软件 编辑:程序博客网 时间:2024/06/05 02:28
需求:假设我们现在有一个系统是web版的,现在我们想不改动很多就移植到手机上,那么我们就需要使用webview组件。
 
一、理论知识:
public class
WebView
extends AbsoluteLayout
implements ViewGroup.OnHierarchyChangeListener ViewTreeObserver.OnGlobalFocusChangeListener
 
java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.AbsoluteLayout
         ↳ android.webkit.WebView
 
Class Overview
 
A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.
 
     这个类包含的方法很多,这里就不一一讲述,我们在实践中来找真理。
 
二、实践
 
 
2.1在assets文件夹里面新建一个test.html页面
 <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<title>android学习</title>
<script language="javascript">
<!--   
  function test()
  {     
    alert(123);
    document.getElementById("divcontent").innerText="hello,world!";
  }     
// -->
</script>
</head>
 
<body>
<a onClick="window.demo.clickOnAndroid()">
<img alt="" src="imgs/icon.png" alt="调用java代码 "><br>
调用java代码 </a>
<br/>
<div id="divcontent"></div>
</body>
</html>
 
 
 
2.2在res/layout文件夹新建webview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <android.webkit.WebView android:id="@+id/webViewtest" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></android.webkit.WebView>
             
</RelativeLayout>
2.3在src文件夹新建WebViewActivity.java
/**
 *
 */
package Test.HelloWorld;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.Html;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.JsResult;
import android.widget.ProgressBar;
/**
 * @author zhuzhifei
 *
 */
public class WebViewActivity extends Activity {
    private WebView mWebView;  
    private static final String LOG_TAG = "BrowserSetting";
    private static final String CACHE_LOCATION = "/data/data/com.snda.figo/cache";
    public void onCreate(Bundle savedInstanceState) {     
        super.onCreate(savedInstanceState);     
        setContentView(R.layout.webview);     
        mWebView = (WebView) findViewById(R.id.webViewtest);     
        this.setBrowser(this, mWebView);
    
      
        //加载在assets文件夹里的页面
      
        mWebView.loadUrl("file:///android_asset/test.html");
        //以下这种写法,将直接跳转到web站点
//        Uri uri = Uri.parse("http://www.snda.com");
//        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//        startActivity(intent);
    } 
    /**
    * setup webView
    *
    * refer to
    * http://hi-android.info/src/com/android/browser/BrowserSettings.java.html
    * for android default browser's settings
    *
    * @param webView
    */
   private  void setBrowser(final Context context, final WebView webView) {
       Log.i(LOG_TAG, "setBrowser with context and mywebview");
       WebSettings webSettings = webView.getSettings();
       // enable js
       Log.i(LOG_TAG, "enable javascript");
       webSettings.setJavaScriptEnabled(true);
       // 设置允许localstorage
       webSettings.setDomStorageEnabled(true);
       // set appcache
       Log.i(LOG_TAG, "set appcache");
       webSettings.setAppCachePath(CACHE_LOCATION);
       webSettings.setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
       webSettings.setAppCacheEnabled(true);
       // set scrollbar style to remove the ugly white edge bar on the right
       Log.i(LOG_TAG,"set scrollbar style to remove the ugly white edge bar on the right");
       webView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        //不保存表单数据
        webView.getSettings().setSaveFormData(false);
        //不保存密码
        webView.getSettings().setSavePassword(false);
        //不支持页面放大功能
        webView.getSettings().setSupportZoom(false);
        webView.setVerticalScrollBarEnabled(false);
        WebView.enablePlatformNotifications();
 
     // 设置WebChromeClient之后js alert confirm才会生效
       webView.setWebChromeClient(new WebChromeClient() {
          //override alert dialog by using js
          @Override
          public boolean onJsAlert(WebView view, String url, String message,
                 final JsResult result) {
              Log.i(LOG_TAG, "alertdialog shows with" + message);
              addVibrator(view);
              AlertDialog.Builder dialog = new AlertDialog.Builder(context);
              dialog.setTitle("提示信息");
              dialog.setMessage(Html.fromHtml(message));
              dialog.setPositiveButton("确定",
                     new DialogInterface.OnClickListener() {
                        public void onClick(
                               DialogInterface dialoginterface, int i) {
                            result.confirm();
                        }
                     });
              dialog.setCancelable(false);
              dialog.setInverseBackgroundForced(true);
              dialog.create();
              dialog.show();
              return true;
          }
          //override android confirm dialog by using js
          @Override
          public boolean onJsConfirm(WebView view, String url,
                 String message, final JsResult result) {
              Log.i(LOG_TAG, "onJsConfirm with " + message);
              addVibrator(view);
              AlertDialog.Builder dialog = new AlertDialog.Builder(context);
              dialog.setTitle("提示信息");
              dialog.setMessage(Html.fromHtml(message));
              dialog.setPositiveButton("确定",
                     new DialogInterface.OnClickListener() {
                        public void onClick(
                               DialogInterface dialoginterface, int i) {
                            result.confirm();
                        }
                     });
              dialog.setNeutralButton("取消",
                     new DialogInterface.OnClickListener() {
                        public void onClick(
                               DialogInterface dialoginterface, int i) {
                            result.cancel();
                        }
                     });
              dialog.setCancelable(false);
              dialog.setInverseBackgroundForced(true);
              dialog.create();
              dialog.show();
              return true;
          }
 
          public void onConsoleMessage(String message, int lineNumber,
                 String sourceID) {
              Log.i(LOG_TAG, message + " -- From line " + lineNumber
                     + " of " + sourceID);
          }
          //进度条
          public void onProgressChanged(WebView view, int progress) {
              if (progress == 100) {
                 //MainView.getInstance().setWelcomeHintText("启动进度已完成100%");
              } else {
                //MainView.getInstance().setWelcomeHintText("启动进度已完成" + progress +"%");
              }
          }
       });
       //如果页面中链接,如果希望点击链接继续在当前browser中响应,
       //而不是新开Android的系统browser中响应该链接,必须覆盖 webview的WebViewClient对象。
       webView.setWebViewClient(new WebViewClient() {
           @Override
           public boolean shouldOverrideUrlLoading(WebView webView, String url) {
               webView.loadUrl(url);
               return true;
           }
        
       });
 
       Log.i(LOG_TAG, "addJavascriptInterface");
     
       //注册java对象demo到页面,页面js就直接可以调用这个对象了
       webView.addJavascriptInterface(new Object() {     
            public void clickOnAndroid() {
              //这里可以写相关业务的处理逻辑
                //...
              //调用客户端的相关js方法
              webView.loadUrl("javascript:test()");
            }     
        }, "demo");
 
   }
   /**
    * 添加手机振动
    * @param webView
    */
   private static void addVibrator(WebView webView) {
       Vibrator vibrator = (Vibrator) webView.getContext().getSystemService(Context.VIBRATOR_SERVICE);
       vibrator.vibrate(new long[] { 5, 12, 9, 19 }, -1);
   }
  
}
 
 
 
 
2.4在AndroidManifest.xml添加这个activity
    <activity android:name=".WebViewActivity">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
 
 
 
 
 
 
 
2.5运行效果
0 0
原创粉丝点击