Android WebView学习

项目工程截图:


效果截图:


Code:

/**
 * Demonstrates how to embed a WebView in your activity. Also demonstrates how
 * to have javascript in the WebView call into the activity, and how the activity 
 * can invoke javascript.
 * <p>
 * In this example, clicking on the android in the WebView will result in a call into
 * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
 * will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
 * method.
 * <p>
 * Obviously all of this could have been accomplished without calling into the activity
 * and then back into javascript, but this code is intended to show how to set up the 
 * code paths for this sort of communication.
 *
 */
public class WebViewDemo extends Activity {

    private static final String LOG_TAG = "WebViewDemo";

    private WebView mWebView;

    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);

        mWebView.setWebChromeClient(new MyWebChromeClient());

        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

        mWebView.loadUrl("file:///android_asset/demo.html");
    }

    final class DemoJavaScriptInterface {

        DemoJavaScriptInterface() {
        }

        /**
         * This is not called on the UI thread. Post a runnable to invoke
         * loadUrl on the UI thread.
         */
        public void clickOnAndroid() {
            mHandler.post(new Runnable() {
                public void run() {
                    mWebView.loadUrl("javascript:wave()");
                }
            });

        }
    }

    /**
     * Provides a hook for calling "alert" from javascript. Useful for
     * debugging your javascript.
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(LOG_TAG, message);
            result.confirm();
            return true;
        }
    }
}
要想全面的了解这个还得要看一下这个网页的html代码,尤其是对javascript的处理的部分:

这是demo.html的代码:

<html>
	<script language="javascript">
	    /* This function is invoked by the activity */
		function wave() {
		    alert("1");
			document.getElementById("droid").src="android_waving.png";
			alert("2");
		}
	</script>
	<body>
	    <!-- Calls into the javascript interface for the activity -->
	    <a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
			margin:0px auto;
			padding:10px;
			text-align:center;
			border:2px solid #202020;" >
				<img id="droid" src="android_normal.png"/><br>
				Click me!
		</div></a>
	</body>
</html>
从上面不难看出

 /**
         * This is not called on the UI thread. Post a runnable to invoke
         * loadUrl on the UI thread.
         */
        public void clickOnAndroid() {
            mHandler.post(new Runnable() {
                public void run() {
                    mWebView.loadUrl("javascript:wave()");
                }
            });
        }
这个的作用就是点击的时候,调用那个javascript函数wave。这个函数的注释部分:This is not called on the UI thread. Post a runnable to invoke loadUrl on the UI thread.

public void addJavascriptInterface (Object obj, String interfaceName)

Since: API Level 1

Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript.

IMPORTANT:

  • Using addJavascriptInterface() allows JavaScript to control your application. This can be a very useful feature or a dangerous security issue. When the HTML in the WebView is untrustworthy (for example, part or all of the HTML is provided by some person or process), then an attacker could inject HTML that will execute your code and possibly any code of the attacker's choosing.
    Do not use addJavascriptInterface() unless all of the HTML in this WebView was written by you.
  • The Java object that is bound runs in another thread and not in the thread that it was constructed in.

Parameters
obj The class instance to bind to JavaScript, null instances are ignored.
interfaceName The name to used to expose the instance in JavaScript.
boolean android.os.Handler.post(Runnable r)

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.(在这个程序里面也就是说会在主线程)

Parameters:
r The Runnable that will be executed.
Returns:
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

mWebView.setWebChromeClient(new MyWebChromeClient());
/**
     * Provides a hook for calling "alert" from javascript. Useful for
     * debugging your javascript.
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(LOG_TAG, message);
            result.confirm();
            return true;
        }
    }

public void setWebChromeClient (WebChromeClient client)

Since: API Level 1

Set the chrome handler. This is an implementation of WebChromeClient for use in handling JavaScript dialogs, favicons, titles, and the progress. This will replace the current handler.

Parameters
client An implementation of WebChromeClient.
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭