Android Network-Network picture Viewer

Source: Internet
Author: User
Tags response code

Xml

<?XML version= "1.0"?>-<LinearLayoutTools:context=". Mainactivity "Android:paddingtop= "@dimen/activity_vertical_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingbottom= "@dimen/activity_vertical_margin"android:orientation= "vertical"Android:layout_height= "Match_parent"Android:layout_width= "Match_parent"Xmlns:tools= "Http://schemas.android.com/tools"xmlns:android= "Http://schemas.android.com/apk/res/android"><EditTextAndroid:id= "@+id/et_url"Android:layout_height= "Wrap_content"Android:layout_width= "Fill_parent"Android:text= "Http://www.baidu.com"/><ButtonAndroid:id= "@+id/bt_looksource"Android:layout_height= "Wrap_content"Android:layout_width= "Fill_parent"Android:text= "View Picture"/>-<ScrollViewAndroid:layout_height= "Wrap_content"Android:layout_width= "Wrap_content"><ImageViewAndroid:id= "@+id/img_pic"Android:layout_height= "Match_parent"Android:layout_width= "Match_parent"/></ScrollView></LinearLayout>
Picture View Controls

Java

 PackageCom.itheima.sourcelook;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;Importjava.net.URLConnection;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;Importandroid.text.TextUtils;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast;ImportCOM.ITHEIMA.PICLOOK.R; Public classMainactivityextendsActivityImplementsonclicklistener{PrivateEditText Et_url; PrivateImageView Img_pic; PrivateContext Mcontext; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Mcontext= This; Et_url=(EditText) Findviewbyid (R.id.et_url); Button Bt_looksource=(Button) Findviewbyid (R.id.bt_looksource); Img_pic=(ImageView) Findviewbyid (r.id.img_pic); //two. Set Click eventsBt_looksource.setonclicklistener ( This); System.out.println ("OnCreate method Thread:" +Thread.CurrentThread (). GetName ()); }    //☆☆☆1. Creating a Handler object in the main thread    PrivateHandler Handler =NewHandler () {//☆☆☆2. Overriding the Handlermessage method of handler to receive messages sent from a child thread         Public voidhandlemessage (android.os.Message msg) {//☆☆☆5. Receives the data sent by the child thread and processes the data. Bitmap Bitmap =(Bitmap) msg.obj; //☆☆☆6. Current method belongs to the main thread can do UI updates//Five. Get the content returned by the server and display it on TextViewImg_pic.setimagebitmap (bitmap);//set the picture content of ImageView        };        }; @Override Public voidOnClick (View v) {Try{        //three. Get the URL address of the user input in the Oclick method        FinalString Url_str =Et_url.gettext (). toString (). Trim (); if(Textutils.isempty (url_str)) {Toast.maketext (Mcontext,"URL cannot be empty", 0). Show (); return ; } System.out.println ("Oclick method Thread:" +Thread.CurrentThread (). GetName ()); //Create a child thread to make a network request        NewThread (NewRunnable () {@Override Public voidrun () {Try{System.out.println ("Oclick method runnable Thread:" +Thread.CurrentThread (). GetName ()); //four. Request URL address//1. Create a URL objectURL url =NewURL (URL_STR); //2. Get a URLConnection objectHttpURLConnection connection =(HttpURLConnection) url.openconnection (); //3. Set some request parameters for the URLConnection object, the request method, the connection timeout timeConnection.setrequestmethod ("GET");//Set Request ModeConnection.setconnecttimeout (1000*10);//setting the time-out period//4. Need to determine the response code before obtaining the data for the URL request, 200: Success, 206: Access to partial data success 300: Jump or redirect 400: Error 500: Server Exception                    intCode =Connection.getresponsecode (); if(Code = = 200){                //5. Get valid data and parse the obtained stream data into a stringInputStream InputStream =Connection.getinputstream (); //convert a read stream to a picture drawable, Btimap: Bitmap?????Bitmap Bitmap =Bitmapfactory.decodestream (InputStream); //☆☆☆3. Create a Message object in the child line, in order to carry the data obtained from the child thread to the main thread. Message msg = Message.obtain ();//gets a Message object in which the internal implementation is: If the previous message exists directly back, there is no new message created to returnMsg.obj = bitmap;//encapsulates the acquired data into a MSG. //☆☆☆4. Use the handler object to send a message to the main thread. handler.sendmessage (msg); }                                    }Catch(Exception e) {e.printstacktrace ();                                        }}). Start (); }Catch(Exception e) {e.printstacktrace (); }    }}
mainactivity

BYTE stream operation

 PackageCom.itheima.sourcelook;ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream; Public classStreamutils { Public Staticstring streamtostring (InputStream in) {string result=""; Try{            //create a byte array to write to a streamBytearrayoutputstream out =NewBytearrayoutputstream (); byte[] buffer =New byte[1024]; intLength = 0;  while(length = in.read (buffer))!=-1) {out.write (buffer,0, length);            Out.flush (); } result= Out.tostring ();//convert byte stream to stringOut.close (); }Catch(Exception e) {e.printstacktrace (); }        returnresult; }}
streamutils

Teacher Notes

04 Network Picture Viewer


ADB shell+ input text content; You can enter the content into the input box on your phone.

Convert a read flow to a Bitmap object:

Bitmapfactory: You can convert a file, read stream, and byte array into a Bitmap object.
Bitmap Bitmap = Bitmapfactory.decodestream (InputStream in);

Imageview.setimagebitmap (bitmap);//Set Picture contents

Android Network-Network picture Viewer

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.