Android学习笔记——Day8

浏览器方式一:
public class BrowserIntent extends Activity {
    /** Called when the activity is first created. */
    private EditText urlText;
    private Button goButton;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        urlText = (EditText)this.findViewById(R.id.url_field);
        goButton = (Button)this.findViewById(R.id.go_button);
        goButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                openBrowser();
               
            }
           
        });
       
       urlText.setOnKeyListener(new OnKeyListener(){

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(keyCode==KeyEvent.KEYCODE_ENTER){
                openBrowser();
                return true;
            }
            return false;
        }
          
       });
    }
   
    public void openBrowser(){
        Uri uri = Uri.parse(urlText.getText().toString());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText android:id="@+id/url_field" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_weight="1.0"
        android:lines="1" android:inputType="textUri" android:imeOptions="actionGo" />
    <Button android:id="@+id/go_button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/go_button" />
</LinearLayout>

在Android手机中内置了一款高性能webkit内核浏览器,在SDK中封装为一个叫做WebView组件。
什么是webkit
WebKit是Mac OS X v10.3及以上版本所包含的软件框架(对v10.2.7及以上版本也可通过软件更新获取)。 同时,WebKit也是Mac OS X的Safari网页浏览器的基础。WebKit是一个开源项目,主要由KDE的KHTML修改而来并且包含了一些来自苹果公司的一些组件。
传统上,WebKit包含一个网页引擎WebCore和一个脚本引擎JavaScriptCore,它们分别对应的是KDE的KHTML和KJS。不过, 随着JavaScript引擎的独立性越来越强,现在WebKit和WebCore已经基本上混用不分(例如Google Chrome和Maxthon 3采用V8引擎,却仍然宣称自己是WebKit内核)。

浏览器方式二:
package com.example.browserintent;

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

public class BrowserView extends Activity {
    private WebView webView;
    private EditText urlText;
    private Button goButton;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.browserview);
        urlText = (EditText) this.findViewById(R.id.view_url_field);
        goButton = (Button) this.findViewById(R.id.view_go_button);
        webView = (WebView)this.findViewById(R.id.web_view);
        Log.d("BrowserView:","urlText*********************"+urlText);
        Log.d("BrowserView:","goButton*********************"+goButton);
        goButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                openBrowser();
            }
        });
        urlText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    openBrowser();
                    return true;
                }
                return false;
            }
        });
    }

    private void openBrowser() {
        /*
         *  1)addJavascriptInterface( ): Allows a Java object to be accessed from
            JavaScript (more on this one in the next section)
            2)createSnapshot( ): Creates a screenshot of the current page
            3)getSettings( ): Returns a WebSettings object used to control the
            settings
            4)loadData( ): Loads the given string data into the browser
            5)loadDataWithBaseURL( ): Loads the given data using a base URL
            6)loadUrl( ): Loads a web page from the given URL
            7)setDownloadListener( ): Registers callbacks for download events,
            such as when the user downloads a .zip or .apk file
            8)setWebChromeClient( ): Registers callbacks for events that need to
            be done outside the WebView rectangle, such as updating the title
            or progress bar or opening a JavaScript dialog box
            9)setWebViewClient( ): Lets the application set hooks in the browser to
            intercept events such as resource loads, key presses, and authorization
            requests
            10)stopLoading( ): Stops the current page from loading
         */
        webView.getSettings().setJavaScriptEnabled(true);
        /*
         * The loadUrl( ) method causes the browser engine to begin loading and
            displaying a web page at the given address. It returns immediately even
            though the actual loading may take some time (if it finishes at all).
         */
        webView.loadUrl(urlText.getText().toString());
    }
}

<?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 android:orientation="horizontal"
        android:layout_width="fill_parent" android:layout_height="wrap_content">
        <EditText android:id="@+id/view_url_field" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_weight="1.0"
            android:lines="1" android:inputType="textUri" android:imeOptions="actionGo" />
        <Button android:id="@+id/view_go_button" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="@string/go_button" />
    </LinearLayout>
    <WebView android:id="@+id/web_view" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_weight="1.0" />
</LinearLayout>


在开发过程中应该注意几点:
    1.AndroidManifest.xml中必须使用许可"android.permission.INTERNET",否则会出Web page not available错误。
    2.如果访问的页面中有Javascript,则webview必须设置支持Javascript。
        webview.getSettings().setJavaScriptEnabled(true);
    3.如果页面中链接,如果希望点击链接继续在当前browser中响应,而不是新开Android的系统browser中响应该链接,必须覆盖 webview的WebViewClient对象。


这里我们初步体验一下在android是使用webview浏览网页,在SDK的Dev Guide中有一个WebView的简单例子 。

mWebView.setWebViewClient(new WebViewClient(){       
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {       
                        view.loadUrl(url);       
                        return true;       
                    }       
        });  

4.如果不做任何处理,浏览网页,点击系统“Back”键,整个Browser会调用finish()而结束自身,如果希望浏览的网 页回退而不是推出浏览器,需要在当前Activity中处理并消费掉该Back事件。

public boolean onKeyDown(int keyCode, KeyEvent event) {       
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {       
            mWebView.goBack();       
                   return true;       
        }       
        return super.onKeyDown(keyCode, event);       
    }    

下一步让我们来了解一下android中webview是如何支持javascripte自定义对象的,在w3c标准中js有 window,history,document等标准对象,同样我们可以在开发浏览器时自己定义我们的对象调用手机系统功能来处理,这样使用js就可以 为所欲为了。

看一个实例:

view plaincopy to clipboardprint?
public class WebViewDemo extends Activity {        
    private WebView mWebView;       
    private Handler mHandler = new Handler();       
       
    public void onCreate(Bundle icicle) {       
        super.onCreate(icicle);       
        setContentView(R.layout.webviewdemo);       
        mWebView = (WebView) findViewById(R.id.webview);       
        WebSettings webSettings = mWebView.getSettings();       
        webSettings.setJavaScriptEnabled(true);       
        mWebView.addJavascriptInterface(new Object() {       
            public void clickOnAndroid() {       
                mHandler.post(new Runnable() {       
                    public void run() {       
                        mWebView.loadUrl("javascript:wave()");       
                    }       
                });       
            }       
        }, "demo");       
        mWebView.loadUrl("file:///android_asset/demo.html");       
    }       
}  


我们看addJavascriptInterface(Object obj,String interfaceName)这个方法,该方法将一个java对象绑定到一个javascript对象中,javascript对象名就是 interfaceName(demo),作用域是Global。这样初始化webview后,在webview加载的页面中就可以直接通过 javascript:window.demo访问到绑定的java对象了。来看看在html中是怎样调用的。

<html>       
        <mce:script language="javascript"><!--     
       
                function wave() {       
                    document.getElementById("droid").src="android_waving.png";       
                }       
             
// --></mce:script>       
        <body>       
            <a onClick="window.demo.clickOnAndroid()">       
                                <img id="droid" src="android_normal.png" mce_src="android_normal.png"/><br>       
                                Click me!       
            </a>       
        </body>       
</html>     
<html>    
        <mce:script language="javascript"><!--  
    
                function wave() {    
                    document.getElementById("droid").src="android_waving.png";    
                }    
          
// --></mce:script>    
        <body>    
            <a onClick="window.demo.clickOnAndroid()">    
                                <img id="droid" src="android_normal.png" mce_src="android_normal.png"/><br>    
                                Click me!    
            </a>    
        </body>    
</html>   

这样在javascript中就可以调用java对象的clickOnAndroid()方法了,同样我们可以在此对象中定义很多方法(比 如发短信,调用联系人列表等手机系统功能。),这里wave()方法是java中调用javascript的例子。

这里还有几个知识点:

1)为了让WebView从apk文件中加载assets,Android SDK提供了一个schema,前缀为"file:///android_asset/"。WebView遇到这样的schema,就去当前包中的 assets目录中找内容。如上面的"file:///android_asset/demo.html"
2)addJavascriptInterface方法中要绑定的Java对象及方法要运行另外的线程中,不能运行在构造他的线程中,这也是使用 Handler的目的。


0RVAX0AJdhcBsgJHj2NfDRnFBB9xR1pCq4eo6IQ

原文地址:https://www.cnblogs.com/yhlx/p/2166552.html