I. Overview
Suffix.
Ii. Requirements
Obtain and display images from the specified URL.
Iii. Implementation
Create a project myurl, modify the main. xml file, and add an imageview in it, as shown below:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent"
5 android:orientation="vertical" >
6
7 <ImageView
8 android:id="@+id/img"
9 android:layout_width="fill_parent"
10 android:layout_height="fill_parent"
11 />
12
13 </LinearLayout>
Modify the myurlactivity. Java file to instantiate the URL object, obtain the input stream of the URL object, then decode the input stream into an image, and finally display the image. The complete content is as follows:
1 package com. Nan. url;
2
3 Import java. Io. ioexception;
4 Import java. Io. inputstream;
5 import java.net. malformedurlexception;
6 Import java.net. url;
7
8 Import Android. App. activity;
9 Import Android. Graphics. Bitmap;
10 Import Android. Graphics. bitmapfactory;
11 import Android. OS. Bundle;
12 Import Android. widget. imageview;
13
14 public class myurlactivity extends Activity
15 {
16 private imageview mimageview = NULL;
17 Private URL murl = NULL;
18 private bitmap mbitmap = NULL;
19 private inputstream minputstream = NULL;
20
21/** called when the activity is first created .*/
22 @ override
23 public void oncreate (bundle savedinstancestate)
24 {
25 super. oncreate (savedinstancestate );
26 setcontentview (R. layout. Main );
27
28 mimageview = (imageview) This. findviewbyid (R. Id. IMG );
29
30 try {
31 // image address
32 murl = new URL ("http://www.android.com/images/sxsw-promo.png ");
33} catch (malformedurlexception e ){
34 // todo auto-generated Catch Block
35 E. printstacktrace ();
36}
37
38 try {
39 // get the URL input stream
40 minputstream = murl. openstream ();
41} catch (ioexception e ){
42 // todo auto-generated Catch Block
43 E. printstacktrace ();
44}
45 // decode the input stream
46 mbitmap = bitmapfactory. decodestream (minputstream );
47 // display the image
48 mimageview. setimagebitmap (mbitmap );
49
50 try {
51 // close the input stream
52 minputstream. Close ();
53} catch (ioexception e ){
54 // todo auto-generated Catch Block
55 E. printstacktrace ();
56}
57
58}
59
60}
Finally, modify the androidmanifest. xml file and add the following network access permissions:
1 <uses-permission android:name="android.permission.INTERNET"/>
Run the program: