[WebView 3]: Use WebView to create Apps and webviewapps

Source: Internet
Author: User

[WebView 3]: Use WebView to create Apps and webviewapps

We learned from the previous article ([WebView 2]: using Web Apps to support screens with different resolutions). Let's continue learning today.

(Blog address: http://blog.csdn.net/developer_jiangqq), reprint please note.

Author: hmjiangqq

Email: jiangqqlmj@163.com

If you want to use a common Web application (or just a Web page) as part of a client application, you can use WebView. WebView is an inheritance and AndroidView class. You can display Web pages as part of the Activity layout. This does not include all functions of the AndroidWeb browser (for example, there is no navigation bar or address bar). All webviews are only a Web page by default.

A common Application scenario is: you may need to update the user terminal protocol or user guide information in the Application by using ViewView. In your Android Application, you can create an Activity with the WebView control and display your documents online.

Another application scenario is: if your application always needs to connect to the network to obtain data (for example, mail ). In this case, the Android Application uses WebView to display all user data instead of executing a network request and then following the data for layout display. On the contrary, you can implement a WebView In the Android Application to design and load Web pages.

This article mainly explains how to start using WebView and some other things, such as processing page navigation and binding Javascript from Web pages to client code in your AndroidApplication.

 

(1): Add WebView in your AndroidApplication

To add a WebView to your Application, simply add the <WebView> tag to your Activity layout. The following is an example layout of a WebView that overwrites the full screen.

<?xml version="1.0" encoding="utf-8"?><WebView  xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/webview"    android:layout_width="fill_parent"    android:layout_height="fill_parent"/>

Then, use the loadUrl () method to load a webpage in WebView.

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.loadUrl("http://www.baidu.com");

Before running, our applications need access. Do not forget to add INTERNET access permissions in your configuration file, such

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

The above is a basic WebView.

 

(2) use Javascript (Using JavascriptInWebView) in WebView)

If you use Javascript in the web page loaded in WebView, you must enable Javascript support for your WebView. Once Javascript is supported, you can create interfaces between your application code and Javascript code.

1. Enabing Javascript)

Javascript is disabled by default in WebView. You can call getSettings () through WebSettings to obtain the WebSettings object and set setJavaScriptEnab led (true) to enable Javascript support. For example:

WebView myWebView = (WebView) findViewById(R.id.webview);WebSettings webSettings = myWebView.getSettings();webSettings.setJavaScriptEnabled(true);

WebSettings also provides a series of other setting methods that may be useful to you. For example, if you develop a WebView-based WebApp for Android applications, you can call

SetUserAgentString () is used to customize the setting of user proxy, so that you can verify whether the request on your Web page is from the Android client.

2. BindingJavaScriptcode to Androidcode)

When we design a WebView-based Web Application in AndroidApplication, you can create interfaces between Javascript code and Android client code. For example, Javascript can call the Andriod code method to display a Dialog box instead of directly using the Javascript alert () method.

You can call the addJavascriptInterface method and use an instance to bind your Javascript code to the class name that needs to be called by Javascript, so that you can bind an interface between javascript code and Android code. Here is an example:

public class WebAppInterface {    Context mContext;    /** Instantiate the interface and set the context */    WebAppInterface(Context c) {        mContext = c;    }    /** Show a toast from the web page */    @JavascriptInterface    public void showToast(String toast) {        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();    }}

[Note]: If you set targetSdkVersion to 17 or higher, you must add the @ JavascriptInterface Annotation on the Javascript method you want to access. If you do not add this annotation, your Web page program will not call this method in Android 4.2 or later versions.

In the preceding example, the WebAppInterface class allows the Web page to use the showToast () method to create a toast message. You can call addJavaScriptInterface to bind the class to Javascript and name it "Android". See the following example:

WebView webView = (WebView) findViewById(R.id.webview);webView.addJavascriptInterface(new WebAppInterface(this), "Android");

We do not need to initialize the Javascript interface named by Android here. WebView will automatically make your Web page accessible. Therefore, when we click the button, the showAndroidTest () method uses the Android interface to call the WebAppInterface. showToast () method.

[Note]: 1. The object bound to Javascript runs in another thread instead of creating a new thread.

2. Use addJavascriptInterface () to allow JavaScript to control Android applications. This is a very useful feature and causes serious security problems. Once the HTML in WebView is unreliable (for example, some or all of the HTML code is provided by an unknown person or unknown process ), then attackers let your Androi application execute the HTML code provided by it. Unless you write HTML and Javascript in WebView, try not to use the addJavaScriptInterface () method. At the same time, you should also be allowed to navigate to other Web pages not written by you in WebView (on the contrary, you can allow the use of the default Web browser to open external links, in this way, you need to process the control page navigation ).

 

(3) HandingPage Navigation)

When a user clicks a link on a Web page on WebView, Android will enable an application to process the URL by default. Generally, the Web browser will open it by default to process and load these URLs. Of course, you can overwrite this method for your WebView, so that you can use your own WebView to open these links. You can allow users to browse the forward and backward navigation pages of your WebView.

You can use setWebViewClient () to provide a WebViewClient for your own WebView to open these link addresses. Example:

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebViewClient(new WebViewClient());

All the links you click will be loaded in your own WebView.

If you want to control more links, you can create your own WebViewClient to rewrite the shouldOverrideUrlLoading () method. The example is as follows:

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;    }}

This creates a new WebViewClient instance for WebView.

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebViewClient(new MyWebViewClient());

Now, when you click a link, the system will customize the shouldOverrideUrlLoading () method, and check whether the URL matches a special object (such as the one defined above ).

If this method does not match, a false value is returned, indicating that URL loading is not overloaded (WebView is allowed to load the URL according to the default method ). If this does not match, an Intent is created to start a new Activity to process the URLs.

 

(4) Navigating Web page history)

When WebView loads a URL, the historical access page is automatically saved. You can use the goBack () and goForward () Methods to navigate forward or backward.

The following is an example: You can use the return key to perform page rollback.

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {    // Check if the key event was the Back button 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);}

If the WebView has a user access history, the canGoBack () method returns true. Similarly, you can use the canGoBack () method to check whether a historical record exists. If you want to perform this check, if no historical or recent record exists, then goBack () and goForward () method will throw an exception.

 

The subsequent articles will specifically encapsulate a WebView component for this knowledge point, so it is more convenient to use. Please wait...




How to return button events in ios webview to the app

Use of WebView for IOS Learning

1. Use UIWebView to load webpages
Run XCode 4.3 and create a new Single View Application named WebViewDemo.
2. Load WebView
Add the WebView member variable in ViewController. h and add the implementation in ViewController. m.
The network environment of the mobile phone changes in real time. When the network is slow, how can I prompt that the user's webpage is being opened? How can I prompt users when an error occurs when opening a webpage? At this time, we need to know when the webpage will be opened,
When the loading is complete and when an error occurs. We need to implement the <UIWebViewDelegate> protocol.
3. Modify the implementation protocol in ViewController. h as follows:
Press control + command + up key to switch to the ViewController. m file. Here we enter-(void) webView in the file to see the following implementation method:
Several important functions in UIWebView
1.-(void) webViewDidStartLoad :( UIWebView *) called when the webView page starts loading
2.-(void) webViewDidFinishLoad :( UIWebView *) called when the webView page is loaded
3.-(void) webView :( UIWebView *) webView didFailLoadWithError :( NSError *) Call when error webpage loading error

4. Add NSLog to implement these three methods.
Add
[WebView setDelegate: self]; sets the proxy. In this way, the preceding three methods can be called back.
The three methods are implemented as follows:

Run print:
15:20:29. 728 WebViewDemo [1001: f803] webViewDidStartLoad
15:20:29. 991 WebViewDemo [1001: f803] webViewDidFinishLoad
Let's try the error and turn off wifi and run the following command to print the result:

15:23:58. 939 WebViewDemo [1087: f803] webViewDidStartLoad
15:23:59. 016 WebViewDemo [1087: f803] webViewDidFinishLoad
The request results remain unchanged. Why is network disconnection still successful? Cache? I will try 163.com. This is the real result:
15:24:41. 131 WebViewDemo [1134: f803] webViewDidStartLoad
15:24:41. 149 WebViewDemo [1134: f803] didFailLoadWithError: Error Domain = NSURLErrorDomain Code =-1009 "The Internet connection appears to be offline. "UserInfo = 0x6b41660 {NSErrorFailingURLStringKey = www.163.com/, NSErrorFailingU ...... remaining full text>
 
In Android development, the WebView component is used to display web pages, while clicking content in the web page opens the browser browsing. How does one default WebView browsing?

If you want to click the link for processing by yourself, instead of the link in the browser of the new Android system. Add an event listening object (WebViewClient) to WebView and rewrite some of the Methods: shouldOverrideUrlLoading: Response to the hyperlink button in the webpage. When you press a connection, WebViewClient will call this method and pass the parameter: the url to be pressed.
WebView. setWebViewClient (new WebViewClient (){
@ Override
Public boolean shouldOverrideUrlLoading (WebView view, String url ){

View. loadUrl (url); // jump to the new url in the current webview

Return true;
}
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.