Android advanced exercise-perform network operations

Source: Internet
Author: User
Perform Network Operations
This section describes how to perform the most basic network connection tasks, manage network connections (including network status changes), and allow users to manage an application network, it also describes how to parse and use XML data. After learning these courses, you can effectively download and parse data from the Internet in an application, and use the least network resources. In this chapter, you will learn how to connect to a network and select an appropriate HTTP client, how can I check the network connection status and create a front-end interface to manage the use of the network when I execute a network operation outside the UI? How can I resolve the network status change?
How to parse XML data and use XML Data Network Operations Best Practices

Obtains the network connection status of the device.
// Checks the network connection and sets the wificonnected and mobileconnected // variables accordingly. private void updateconnectedflags () {// Network Management Service connectivitymanager connmgr = (connectivitymanager) getsystemservice (context. connectivity_service); networkinfo activeinfo = connmgr. getactivenetworkinfo (); If (activeinfo! = NULL & activeinfo. isconnected () {// WiFi connection status wificonnected = activeinfo. getType () = connectivitymanager. type_wifi; // mobile connection status mobileconnected = activeinfo. getType () = connectivitymanager. type_mobile;} else {wificonnected = false; mobileconnected = false ;}}

Use asynctask class to asynchronously execute network connection operations outside the main UI thread
    // Implementation of AsyncTask used to download XML feed from stackoverflow.com.    private class DownloadXmlTask extends AsyncTask<String, Void, String> {        @Override        protected String doInBackground( String... urls) {            try {                return loadXmlFromNetwork(urls[0]);            } catch (IOException e) {                return getResources().getString(R.string.connection_error);            } catch (XmlPullParserException e) {                return getResources().getString(R.string.xml_error);            }        }        @Override        protected void onPostExecute(String result) {            setContentView(R.layout. activity_main);            // Displays the HTML string in the UI via a WebView            WebView myWebView = (WebView) findViewById(R.id. webview);            myWebView.loadData(result, "text/html", null );        }    }

Execute network connection

// Given a string representation of a URL, sets up a connection and gets // an input stream. private inputstream DownLoadURL (string urlstring) throws ioexception {URL url = new URL (urlstring); httpurlconnection conn = (httpurlconnection) URL. openconnection (); // set the timeout time for reading network streams. setreadtimeout (10000/* milliseconds */); // set the network connection timeout value Conn. setconnecttimeout (15000/* milliseconds */); // set it to get request Conn. setrequestmethod ("get"); // you can specify whether to read the network input stream Conn. setdoinput (true); // starts the query Conn. connect (); inputstream stream = Conn. getinputstream (); Return stream ;}

In the Android operating system, a broadcast is sent every time the network status changes. We only need to register the broadcast receiver to know the network status changes.

// Register broadcastreceiver to track connection changes. // dynamically register the broadcast receiver to receive the broadcast intentfilter filter = new intentfilter (connectivitymanager. connectivity_action); receiver = new networkreceiver (); this. registerreceiver (receiver, filter );

/***** This broadcastreceiver intercepts the android.net. connectivitymanager. connectivity_action, * which indicates a connection change. it checks whether the type is type_wifi. * if it is, it checks whether Wi-Fi is connected and sets the wificonnected flag in the * main activity accordingly. * When the network status changes, perform some processing */public class networkreceiver extends broadcastreceiver {@ override public void onrec Eive (context, intent) {connectivitymanager connmgr = (connectivitymanager) context. getsystemservice (context. connectivity_service); networkinfo = connmgr. getactivenetworkinfo (); // checks the user prefs and the network connection. based on the result, decides // whether // to refresh the display or keep the current display. // If the userpref is Wi-Fi only, checks to se E if the device has a Wi-Fi connection. If (WiFi. Equals (spref) & networkinfo! = NULL & networkinfo. getType () = connectivitymanager. type_wifi) {// If device has its wi-fi connection, sets refreshdisplay // to true. this causes the display to be refreshed when the user // returns to the app. refreshdisplay = true; toast. maketext (context, R. string. wifi_connected, toast. length_short ). show (); // if the setting is any network and there is a network connection // (which by PR Ocess of elimination wocould be mobile), sets refreshdisplay to true.} else if (any. Equals (spref) & networkinfo! = NULL) {refreshdisplay = true; // otherwise, the app can't download content -- either because there is no network // connection (mobile or Wi-Fi ), or because the Pref setting is WiFi, And there // is no Wi-Fi connection. // sets refreshdisplay to false .} else {refreshdisplay = false; toast. maketext (context, R. string. lost_connection, toast. length_short ). show ();}}}

Best practices for parsing XML using the android SDK's own parser pull

// Configure parser. setfeature (xmlpullparser. feature_process_namespaces, false) without using the namespace feature to save resources and speed up resolution );

// Test whether it is the start of a tag. It supports any namespace and the tag name is feed. effectively reduce some invalid parsing operations parser. require (xmlpullparser. start_tag, NS, "Feed ");

// Skips tags the parser isn' t interested in. uses depth to handle nested tags. i. E ., // if the next tag after a start_tag isn't a matching end_tag, it keeps going until it // finds the matching end_tag (as indicated by the value of "depth" being 0 ). // skip some useless tags and do not parse them. You do not need to judge whether the current tag is the one we need every time. This will speed up the parsing of private void SKIP (xmlpullparser parser) throws xmlpullparserexception, ioexception {If (parser. ge Teventtype ()! = Xmlpullparser. start_tag) {Throw new illegalstateexception ();} int depth = 1; while (depth! = 0) {Switch (parser. Next () {Case xmlpullparser. end_tag: depth --; break; Case xmlpullparser. start_tag: Depth ++; break ;}}}

Summary

To execute a network task in Android, it is generally executed in a thread other than the main UI thread to avoid blocking the main UI thread, listening to changes in the network status, and then doing some operations, is necessary! This helps our applications provide a better user experience. XML data parsing also needs to be optimized to display data to users at a faster speed. These are good practices.

Sample: http://www.android-doc.com/training/basics/network-ops/index.html

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.