In this small series to learn to view the network pictures of the small case,:
Initial interface:
When you click Browse, the effect is as follows:
It is important to note that this case requires access to networking, namely:
<uses-permission android:name= "Android.permission.INTERNET"/>
The steps are as follows:
1. Define and initialize the control:
Private EditText Etimageurl; Private ImageView Ivimage;
/** Control Initialization */ Private void init () { = (ImageView) Findviewbyid (r.id.ivimage); = (EditText) Findviewbyid (R.id.etimageurl); }
2. Establish the Handler object:
PrivateHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {//to process the received messages//Looper.prepare (); Switch(msg.what) { CaseShow_image:bitmap Bitmap= (Bitmap) msg.obj;//To cast an object in the OS stream to a bitmapIvimage.setimagebitmap (bitmap); Toast Toast= Toast.maketext (mainactivity. This, "Picture loaded successfully", Toast.length_short); Toast.setgravity (0, 0, 100); Toast.show (); Break; default: Break; } }; };
3. Set the method for displaying the network picture:
Public voidShowImage (view view) {//if the onclick () attribute is used in an XML file, its method format must be the method name (view view) FinalString Path =Etimageurl.gettext (). toString (); if(Textutils.isempty (path)) {Toast.maketext (mainactivity. This, "Picture path cannot be empty", Toast.length_short). Show (); } Else { NewThread () { Public voidrun () {//linked server, request for picture Try{URL URL=NewURL (path); //make an HTTP requestHttpURLConnection httpurlconnection =(HttpURLConnection) url.openconnection (); Httpurlconnection.setrequestmethod ("GET"); //Set link timeout timeHttpurlconnection.setconnecttimeout (5000); intResponsecode = Httpurlconnection.getresponsecode ();//Get the response code if(Responsecode = = 200) {InputStream is= Httpurlconnection.getinputstream ();//Get input streamBitmap Bitmap =Bitmapfactory.decodestream (IS); //2. Tell the main thread, help me update the interface, the content is bitmapMessage msg =NewMessage (); Msg.what=Show_image; Msg.obj=bitmap; Handler.sendmessage (msg); }Else{toast Toast= Toast.maketext (mainactivity. This, "Picture failed to load", Toast.length_short); Toast.setgravity (0, 0, 100); Toast.show (); } } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }}}.start ();//Be sure to start the thread } }
At this point, a small case of viewing the network picture is complete.
Android Learning View Network pictures