Android uses URLs to display network pictures

Source: Internet
Author: User

Ching

Original address: http://blog.csdn.net/qingdujun/article/details/39271479


A few methods are very easy to understand in the URL object, and the OpenStream () provided by the object can read the InputStream of the URL resource, which makes it very easy to read remote resources.

The following program demonstrates how to read a remote resource from a URL class:

1) Show only network pictures

2) display and download network pictures


1) Show only network pictures


A) Activity_main.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=" dujun.king.urlgetimage.MainActivity ">    <imageview        Android:id= "@+id/imageview1"        android:layout_width= "wrap_content"        android:layout_height= "wrap_content "        android:layout_alignparentbottom=" true "        android:layout_centerhorizontal=" true "        android:layout _marginbottom= "196DP"        android:src= "@drawable/ic_launcher"/></relativelayout>

b) Mainactivity.java

Package Dujun.king.urlgetimage;import Java.io.inputstream;import Java.net.url;import android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.os.Handler; Import Android.os.message;import android.view.menu;import android.view.menuitem;import Android.widget.ImageView;    public class Mainactivity extends Activity {Bitmap Bitmap;        ImageView ImageView; Handler handler=new Handler () {@Override public void Handlemessage (Message msg) {if (msg.what==0            x9527) {//display pictures downloaded from the Internet imageview.setimagebitmap (bitmap);        }        }              };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);             imageview= (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); Create and start a new thread to download the picture from the network new thread () {@Override public void run () {               try {//Create a URL object url url=new url ("http://www.baidu.com/img/bdlogo.pn                    G ");                    Open the URL corresponding to the resource input stream InputStream is= url.openstream ();                Parse the picture from the InputStream stream bitmap = Bitmapfactory.decodestream (IS);                     Imageview.setimagebitmap (bitmap);                    Sends a message informing the UI component that the picture Handler.sendemptymessage (0x9527) is displayed;                Close the input stream is.close ();                } catch (Exception e) {e.printstacktrace ();        }}}.start (); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}
c) androidmainifest.xml

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Dujun.king.urlgetimage "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk  android:minsdkversion= "android:targetsdkversion="/><!--access to Internet rights--><uses-permission Android:name= "Android.permission.INTERNET"/> <application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <act Ivity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </application></manifest>

2) If we want to display and download the network image, we just need to modify the Mainactivity.java file as follows:

Package Dujun.king.urlgetimage;import Java.io.inputstream;import Java.io.outputstream;import java.net.URL;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.view.menu;import    Android.view.menuitem;import Android.widget.imageview;public class Mainactivity extends Activity {Bitmap Bitmap;        ImageView ImageView; Handler handler=new Handler () {@Override public void Handlemessage (Message msg) {if (msg.what==0            x9527) {//display pictures downloaded from the Internet imageview.setimagebitmap (bitmap);        }        }              };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);             imageview= (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); Create and start a new thread for downloading pictures from the network///Here must be a new thread, Android later in the version, not allowed in the main thread in the network       New Thread () {@Override public void run () {try {//Create a URL                    Object URL url=new url ("Http://www.baidu.com/img/bdlogo.png");                    Open the URL corresponding to the resource input stream InputStream is= url.openstream ();                Parse the picture from the InputStream stream bitmap = Bitmapfactory.decodestream (IS);                     Imageview.setimagebitmap (bitmap);                    Sends a message informing the UI component that the picture Handler.sendemptymessage (0x9527) is displayed;                    Close the input stream is.close (); ------------------------------//Download network image//open resource flow again is = Url.open                    Stream (); Open the corresponding output stream of the phone//stored in the phone, and named baidulogo.png outputstream OS = Openfileoutput ("Baidulogo.                    PNG ", mode_world_readable);                    byte[] buff = new byte[1024];         int len = 0;           Because the network download is generally not possible once downloaded, we will download the valid data each time to write while ((len = is.read (buff)) > 0)                    {Os.write (Buff,0,len);                    }//Close stream is.close ();                Os.close ();                } catch (Exception e) {e.printstacktrace ();    }}}.start (); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid (); if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}


References: Crazy Android Handout (2nd edition) Li Gang authoring

Original address: http://blog.csdn.net/qingdujun/article/details/39271479

Android uses URLs to display network pictures

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.