一、概述
URL,說白了就是一個網路地址(網址),通常一個網址裡包含很多內容,這裡要講的不是如何從一個包括很多內容(比如很多圖片)的網址裡找到自己感興趣的內容(比如說某一張圖片),而是從一個帶有圖片格式(.jpg、.png、.bmp等)尾碼的網址裡擷取該圖片,也就是說該網址裡只有一張圖片。
二、要求
從指定的網址裡擷取圖片並顯示出來。
三、實現
建立工程MyURL,修改main.xml檔案,在裡面添加一個ImageView,如下:
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>
修改MyURLActivity.java檔案,主要是執行個體化URL對象,接著擷取URL對象的輸入資料流,再將該輸入資料流解碼成圖片,最後把該圖片顯示出來。完整的內容如下:
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 //圖片地址
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 //獲得URL的輸入資料流
40 mInputStream = mURL.openStream();
41 } catch (IOException e) {
42 // TODO Auto-generated catch block
43 e.printStackTrace();
44 }
45 //解碼輸入資料流
46 mBitmap = BitmapFactory.decodeStream(mInputStream);
47 //顯示圖片
48 mImageView.setImageBitmap(mBitmap);
49
50 try {
51 //關閉輸入資料流
52 mInputStream.close();
53 } catch (IOException e) {
54 // TODO Auto-generated catch block
55 e.printStackTrace();
56 }
57
58 }
59
60 }
最後,修改AndroidManifest.xml檔案,加入訪問網路的許可權:
1 <uses-permission android:name="android.permission.INTERNET"/>
運行該程式: