[每天学点Android开发]Building Web Apps in WebView

今日学习任务:理解Android Web Apps的运行机制,实现简单的包含Web View的应用程序

涉及的主要内容:1) Android Web Apps的两种形式 2)Web View的创建和使用方法    

  1. Web Apps的两种形式

    在Android中,Web Apps有两种形式供用户访问。一种就是用手机上的浏览器直接访问的网络应用程序,这种情况用户不需要额外安装其他应用,只要有浏览器就行;而另一种,则是在用户的手机上安装客户端应用程序(.apk),并在此客户端程序中嵌入Web View来显示从服务器端下载下来的网页数据,比如新浪微博和人人网的客户端。对于前者来说,主要的工作是根据手机客户端的屏幕来调整网页的显示尺寸、比例等;而后者需要单独开发基于Web View的Web app. 本篇主要是学习后者的开发。

      

     (图片来源于:developer.android.com) 

  2. 怎样在Android应用程序中加入Web View?

    2.1 先在layout文件中加入<WebView>元素

< WebView   xmlns:android ="http://schemas.android.com/apk/res/android"
    android:id
="@+id/webview"
    android:layout_width
="fill_parent"
    android:layout_height
="fill_parent" />

    2.2 由于应用程序需要访问网络,所以需要在AndroidManifest.xml中请求网络权限的:

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

    2.3 使用Web View:

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

    2.4 加载一个页面,可以用loadUrl()方法,例如:

 
    
 myWebView.loadUrl("http://www.xxx.com");

   3. 在Web View 中使用JavaScript 

     3.1 如果你加载到 Web View 中的网页使用了JavaScript,那么,需要在Websetting 中开启对JavaScript的支持,因为Web View 中默认的是JavaScript未启用。

//  获取 WebSetting 

WebSettings webSettings = myWebView.getSettings();

 

//  开启Web View对JavaScript的支持

webSettings.setJavaScriptEnabled(true);

     3.2 将JavaScript与Android客户端代码进行绑定。

       为什么要绑定呢? 可以看这个例子:如果JavaScript 代码想利用Android的代码来显示一个Dialog,而不用JavaScript的alert()方法,这时就需要在Android代码和JavaScript代码间创建接口,这样在Android代码中实现显示对话框的方法,然后JavaScript调用此方法。

      1)创建 Android代码和JavaScript代码的接口,即创建一个类,类中所写的方法将被JavaScript调用

  public class JavaScriptInterface {  

  Context mContext;

    /** 初始化context,供makeText方法中的参数来使用 */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    
/** 创建一个方法,实现显示对话框的功能,供JavaScript中的代码来调用 */
    
public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

}  

     2)通过调用addJavascriptInterface方法,把我们上面创建的接口类绑定与运行在Web View上的JavaScript进行绑定。

// 第二个参数是为这个接口对象取的名字,以方便JavaScript调用

webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

       3)现在,我们可以在html中的JavaScript部分调用showToast()方法了。

< script  type ="text/javascript" >
    
function  showAndroidToast(toast) {
        Android.showToast(toast);
    }
</ script >

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" /> 

 

    4. 处理页面导航

     当用户在Web View中点击页面上的超链接时, Android的默认行为是启动一个能处理URL的应用程序,通常情况下是启动默认的浏览器。而如果我们想用当前的Web View打开页面,则需要重载这个行为。这样我们就可以通过操作Web View的历史记录来向前和向后导航。

      4.1 为Web View提供一个WebViewClient,从而在WebView中打开用户的链接。 如果我们想对加载页面有跟多的控制,可以继承并实现一个复杂的WebViewClient

 myWebView.setWebViewClient( new  WebViewClient()); 
  private   class  MyWebViewClient  extends  WebViewClient {
    @Override
    
public   boolean  shouldOverrideUrlLoading(WebView view, String url) {
        
if  (Uri.parse(url).getHost().equals( " www.example.com " )) {
            
//  This is my web site, so do not override; let my WebView load the page
             return   false ;
        }
        
//  Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent  =   new  Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        
return   true ;
    }

     4.2 利用Web View的历史记录来实现页面navigate backword.

     重载Activity中的onKeyDown方法,实现此功能:

 @Override

 public boolean onKeyDown(int keyCode, KeyEvent event) {

     //  Check if the key event was the BACK key and if there's history
    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() {
        myWebView.goBack();
        return true;
    }
     //  If it wasn't the BACK key or there's no web page history, bubble up to the default
     //  system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}


   5. 现在应用以上知识,实现一个简单的基于Web View的Android 应用程序

    程序的功能主要是:当进入程序后,显示一个网页,此页面上有一个新闻超链接,用户点击超链接,在Web View中加载新闻的内容页面。

    5.1 创建含有Web View的Activity:Home.java

package  com.WebApp;
import  android.app.Activity;
import  android.os.Bundle;
import  android.view.KeyEvent;
import  android.webkit.WebSettings;
import  android.webkit.WebView;

public   class  Home  extends  Activity {
    
//  declare a WebView
     private  WebView myWebView;

    @Override
    
public   void  onCreate(Bundle icicle) {
        
super .onCreate(icicle);
        setContentView(R.layout.main);
        
        
//  initialize the WebView
        myWebView  =  (WebView) findViewById(R.id.webview);
        
        
/*  Enable the JavaScript in Web View  */
        WebSettings webSettings 
=  myWebView.getSettings();
        webSettings.setJavaScriptEnabled(
true );

        
//  bind the Android code to JavaScript code
        myWebView.addJavascriptInterface( new  myJavaScriptInterface(),  " myJS " );
        
        
//  load a web page
        myWebView.loadUrl( " file:///android_asset/first.html " );
    }

    
/**
     * This class is an interface between Android and JavaScript
     * whose methods can be accessed by JavaScript code
     
*/
    
final   class  myJavaScriptInterface {

        myJavaScriptInterface() {
        }

        
/**
         * load the content page
         
*/
        
public   void  LoadContentPage() {
            myWebView.loadUrl(
" file:///android_asset/second.html " );
        }
    }
    
    @Override
    
public   boolean  onKeyDown( int  keyCode, KeyEvent event) {
        
//  Check if the key event was the BACK key and if there's history
         if  ((keyCode  ==  KeyEvent.KEYCODE_BACK)  &&  myWebView.canGoBack()){
            myWebView.goBack();
            
return   true ;
        }
        
//  If it wasn't the BACK key or there's no web page history, bubble up to the default
        
//  system behavior (probably exit the activity)
         return   super .onKeyDown(keyCode, event);
    }
}

    5.2 在Android项目文件下的assets目录下创建一个名为first.html的页面作为首页

 
<html>
        <body>
            <!-- 调用Android代码中的方法 -->
            <a onClick="window.myJS.LoadContentPage()" style="text-decoration: underline">
            Google+ is now under testing!
            </a>
        </body>
</html>

    5.3 在Android项目文件下的assets目录下创建一个名为second.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=ISO-8859-1" >
< title > Google+ is under testing </ title >
</ head >
< body >
 Google+ is in limited Field Trial Right now, we're testing with a small number of people, but it won't be long before the Google+ project is ready for everyone. Leave us your email address and we'll make sure you're the first to know when we're ready to invite more people.
</ body >

</html>  

    5.4 运行程序,测试

 

参考:http://developer.android.com/guide/webapps/webview.html 

转载于:https://www.cnblogs.com/ruiyi1987/archive/2011/07/01/2095163.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值