Android Official Development Document Training Series Course Chinese version: Network Operation network Connection

Source: Internet
Author: User

Original address: http://android.xsoftlab.net/training/basics/network-ops/index.html

Introduction

This class will learn the most basic network connection, monitor the network connection status and network control and other content. It also comes with a description of how XML data is parsed and used.

The sample code included in this lesson demonstrates the most basic network operating procedures. Developers can use this part of the code as the most basic network operation code of the application.

Through this lesson, will learn the most basic network download and data analysis of the relevant knowledge.

Note: You can view the course transmitting Network Data Using volley learning volley knowledge. This HTTP library makes it easier and faster to operate the network. Volley is an open-source framework library that makes the application's network operations more logical and manageable, and improves the performance of the application.

Connect to a network

This lesson will learn how to implement a simple program that contains network connections. The steps described in the course are the best implementations of network connectivity.

If the app wants to use network operations, the following permissions should be included in the manifest file:

<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Select HTTP Client

Most Android apps use HTTP to send and receive data. Android contains two HTPP clients: HttpURLConnection and Apache HTTP clients. Both support HTTPS, upload, download, time-out configuration, IPv6, connection pooling. We recommend the use of httpurlconnection in gingerbread and above. For more discussion about this topic, see Blog Android's HTTP clients.

Check Network connection Status

Before attempting to connect to the network, you should check that the network connection is available through the Getactivenetworkinfo () method and the IsConnected () method. Remember, the device may be in a network-wide situation, or the user may not have WiFi or mobile data turned on. For more information on this topic, see Managing Network Usage.

publicvoidmyClickHandler(View view) {    ...    ConnectivityManager connMgr = (ConnectivityManager)         getSystemService(Context.CONNECTIVITY_SERVICE);    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();    ifnull && networkInfo.isConnected()) {        // fetch data    else {        // display error    }    ...}
Performing network operations in a child thread

The time spent on network operations is usually indeterminate. In order to prevent a bad user experience due to network operation, this process should be put into a separate thread for execution. The Asynctask class provides help for this implementation. For more discussion on this topic, see Multithreading for performance.

In the following code snippet, the Myclickhandler () method calls the new Downloadwebpagetask (). Execute (stringurl). Class Downloadwebpagetask is a subclass of Asynctask. Downloadwebpagetask implements the following methods of Asynctask:

    • The DownloadURL () method is executed in Doinbackground (). It passes the URL address of the Web page as an argument to the method. The DownloadURL () method obtains and processes the contents of the Web page. When the processing is finished, this method returns the processed results.
    • OnPostExecute () Gets the result returned after it is displayed on the UI.
 Public  class httpexampleactivity extends Activity {    Private Static FinalString Debug_tag ="Httpexample";PrivateEditText Urltext;PrivateTextView TextView;@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);           Setcontentview (R.layout.main);        Urltext = (EditText) Findviewbyid (R.id.myurl);    TextView = (TextView) Findviewbyid (R.id.mytext); }//When user clicks button, calls Asynctask.    //Before attempting to fetch the URL, makes sure this there is a network connection.     Public void Myclickhandler(View view) {//Gets the URL from the UI ' s text field.String StringUrl = Urltext.gettext (). toString ();        Connectivitymanager connmgr = (connectivitymanager) getsystemservice (Context.connectivity_service); Networkinfo networkinfo = Connmgr.getactivenetworkinfo ();if(Networkinfo! =NULL&& networkinfo.isconnected ()) {NewDownloadwebpagetask (). Execute (stringurl); }Else{Textview.settext ("No network connection available."); }    }//Uses Asynctask to create a task away from the main UI thread. This task takes a     //URL string and uses it to the create an httpurlconnection. Once the connection     //has been established, the Asynctask downloads the contents of the webpage as     //an inputstream. Finally, the InputStream is converted to a string, which is     //displayed in the UI by the Asynctask ' s OnPostExecute method.     Private  class downloadwebpagetask extends asynctask<String, Void , String> {        @Override        protectedStringDoinbackground(String ... URLs) {//params comes from the Execute () call:params[0] is the URL.            Try{returnDownloadURL (urls[0]); }Catch(IOException e) {return "Unable to retrieve web page. URL may invalid. "; }        }//OnPostExecute Displays the results of the asynctask.        @Override        protected void OnPostExecute(String result)       {Textview.settext (result); }    }    ...}

The code above performs the following actions:

    • 1. When the user presses the button, the Myclickhandler () method is called, and the app passes the specified URL address to downloadwebpagetask.
    • The Doinbackground () method of 2.DownloadWebpageTask calls the DownloadURL () method.
    • The 3.downloadUrl () method creates a URL object as a parameter for the obtained URL string.
    • The 4.URL object is used to establish a connection to the httpurlconnection.
    • 5. Once the connection is established, HttpURLConnection will enter the retrieved Web page content as the input stream.
    • The 6.readIt () method converts the input stream to a string object.
    • 7. The last OnPostExecute () method displays the string object on the UI.
Connect and download Data

You can use HttpURLConnection to perform a GET request and download input in a thread that performs a network transfer. After the Connect () method is called, data in the form of an input stream can be obtained through the getInputStream () method.

The DownloadURL () method is called in the Doinbackground () method. The DownloadURL () method uses the URL as a parameter to establish a connection to the network through HttpURLConnection. Once the connection is established, the application uses the getInputStream () method to receive data in the form of a byte stream.

//Given a URL, establishes an httpurlconnection and retrieves//The Web page content as a inputstream, which it returns as//a string.PrivateStringDownloadURL(String Myurl)throwsIOException {InputStream is =NULL;//Only display the first characters of the retrieved    //Web page content.    intLen = -;Try{URL url =NewURL (Myurl);        HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (10000 / * milliseconds * /); Conn.setconnecttimeout (15000 / * milliseconds * /); Conn.setrequestmethod ("GET"); Conn.setdoinput (true);//Starts the queryConn.connect ();intResponse = Conn.getresponsecode (); LOG.D (Debug_tag,"The response is:"+ response); is = Conn.getinputstream ();//Convert the InputStream into a stringString contentasstring = Readit (is, Len);returncontentasstring;//makes sure that the InputStream are closed after the app is    //finished using it.}finally{if(Is! =NULL) {is.close (); }     }}

Note the Getresponsecode () method returns the status code of the connection. This status code can be used to obtain additional information about the connection. A status code of 200 indicates a successful connection.

Convert a byte stream to a string

The inputstream reads the byte data. Once the InputStream object is acquired, it is often necessary to decode it or convert it into other types of data. For example, if you download a picture, the byte stream code should be a picture:

null;...Bitmap bitmap = BitmapFactory.decodeStream(is);ImageView imageView = (ImageView) findViewById(R.id.image_view);imageView.setImageBitmap(bitmap);

In the example above, InputStream represents the textual content of a Web page. The following code shows how to convert a byte stream to a string:

// Reads an InputStream and converts it to a String.publicreadItintthrows IOException, UnsupportedEncodingException {    null;    new"UTF-8");            charnewchar[len];    reader.read(buffer);    returnnew String(buffer);}

Android Official Development Document Training Series Course Chinese version: Network Operation network Connection

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.