Android network technology -- Usage of WebView

When an application loads a web page, use the WebView control to embed the browser in the application.

See the following example for details:

Layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
</LinearLayout>

Code in MainActivity

public class MainActivity extends AppCompatActivity {
    private EditText etkl;
    private Button setkl;
    private Button getkl;
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);//Load a new web page based on the incoming parameters
                return true;//Indicates that the current WebView can handle the request to open a new web page without using the system browser
            }

        });
        webView.loadUrl("http://www.baidu.com");
    }

}

First, use the findViewById() method to get an example of WebView, then call the getSettings() method of WebView to set some browser attributes. The setjavascript enabled () method enables WebView to support JavaScript scripts.

Next, we call the setWebViewClient() method of WebView, pass in the anonymous class of WebViewClient as the parameter, and then override the shouldOverrideUrlLoading() method. This shows that when we need to jump from one web page to another, we want the target web page to still be displayed in the current WebView instead of opening the system browser.  

The last step is very simple. Call WebView's loadUrl() method and pass in the web address to display the content of the corresponding web page. Let's see what Baidu's homepage looks like. In addition, it should be noted that since the program uses the network function, and access to the network requires the declaration of permission, we have to modify the AndroidManifest.xml file and add the permission declaration, as shown below:

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

 

Tags: Android xml network encoding

Posted on Sun, 09 Feb 2020 13:14:40 -0500 by mchannel