深入理解Android网络编程——学习笔记(一)——加载一个Web页面

深入理解Android网络编程——学习笔记(一)

平台:Android Stduio

SDK:27

参考文献:http://android-doc.com/

1、加载一个Web页面

(1)在AS(Android Studio)中创建项目

(2)添加字符串。在字符串文件 \res\values\strings.xml 添加需要的字符串

OpenURL

(3)添加Button控件。打开 \res\layout\activity_main.xml,在布局文件中添加Button按钮




    
    

(4)在配置文件中添加网络权限  \manifests\AndroidManifest.xml

主要添加

 全部配置文件代码




    

    
        
            
                

                
            
        
    

(5)加载Web页面,代码在目录 \jave\项目名\MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt1=(Button)findViewById(R.id.open_ulr);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri=Uri.parse("http://www.baidu.com");
                Intent intent=new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
            }
        });
    }
}

(6)运行结果

深入理解Android网络编程——学习笔记(一)——加载一个Web页面_第1张图片

深入理解Android网络编程——学习笔记(一)——加载一个Web页面_第2张图片

2、应用内打开页面,使用WebView控件

(1)修改1.(5)中代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView=(WebView)findViewById(R.id.wv);
        webView.loadUrl("http://translate.google.cn/m");
    }
}

(2)运行结果 

深入理解Android网络编程——学习笔记(一)——加载一个Web页面_第3张图片

3、使用WebView的setWebViewClient()方法

(1)修改1.(5)中代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView=(WebView)findViewById(R.id.wv);
        webView.loadUrl("http://translate.google.cn/m");
        webView.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
                if(request.toString().startsWith("http://translate.google.cn/m")){
                    return false;
                }
                return false;
            }
        });
    }
}

4、【知识点】

(1)Uri.parse()

public static Uri parse (String uriString)

Added in API level 1

Creates a Uri which parses the given encoded URI string.

Parameters

uriString an RFC 2396-compliant, encoded URI

Returns

  • Uri for this given uri string

Throws

NullPointerException if uriString is null

(2)WebView

public class

WebView

extends AbsoluteLayout
implements ViewGroup.OnHierarchyChangeListener ViewTreeObserver.OnGlobalFocusChangeListener

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.AbsoluteLayout
         ↳ android.webkit.WebView

 

Class Overview


 

A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.

Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:

This must be a child of the element.

(2)WebView中loadUrl()方法

public void loadUrl (String url)

Added in API level 1

Loads the given URL.

Parameters

url the URL of the resource to load

 (3)WebView中loadDataWithBaseURL方法

public void loadData (String data, String mimeType, String encoding)

Added in API level 1

Loads the given data into this WebView using a 'data' scheme URL.

Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.

The encoding parameter specifies whether the data is base64 or URL encoded. If the data is base64 encoded, the value of the encoding parameter must be 'base64'. For all other values of the parameter, including null, it is assumed that the data uses ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.

The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

Parameters

data a String of data in the given encoding
mimeType the MIME type of the data, e.g. 'text/html'
encoding the encoding of the data

 

(4)WebView中loadDataWithBaseURL()方法

public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)

Added in API level 1

Loads the given data into this WebView, using baseUrl as the base URL for the content. The base URL is used both to resolve relative URLs and when applying JavaScript's same origin policy. The historyUrl is used for the history entry.

Note that content specified in this way can access local device files (via 'file' scheme URLs) only if baseUrl specifies a scheme other than 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.

If the base URL uses the data scheme, this method is equivalent to calling loadData() and the historyUrl is ignored, and the data will be treated as part of a data: URL. If the base URL uses any other scheme, then the data will be loaded into the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded entities in the string will not be decoded.

Parameters

baseUrl the URL to use as the page's base URL. If null defaults to 'about:blank'.
data a String of data in the given encoding
mimeType the MIMEType of the data, e.g. 'text/html'. If null, defaults to 'text/html'.
encoding the encoding of the data
historyUrl the URL to use as the history entry. If null defaults to 'about:blank'. If non-null, this must be a valid URL.

(5) WebView中setWebViewClient()方法

public void setWebViewClient (WebViewClient client)

Added in API level 1

Sets the WebViewClient that will receive various notifications and requests. This will replace the current handler.

Parameters

client an implementation of WebViewClient

(6)WebView中shouldOverrideUriLoading()

public boolean shouldOverrideUrlLoading (WebView view, String url)

Added in API level 1

Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url. This method is not called for requests using the POST "method".

Parameters

view The WebView that is initiating the callback.
url The url to be loaded.

Returns

  • True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.

 

你可能感兴趣的:(Android)