一、概述
URL,说白了就是一个网络地址(网址),通常一个网址里包含很多内容,这里要讲的不是如何从一个包括很多内容(比如很多图片)的网址里找到自己感兴趣的内容(比如说某一张图片),而是从一个带有图片格式(.jpg、.png、.bmp等)后缀的网址里获取该图片,也就是说该网址里只有一张图片。
二、要求
从指定的网址里获取图片并显示出来。
三、实现
新建工程MyURL,修改main.xml文件,在里面添加一个ImageView,如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
修改MyURLActivity.java文件,主要是实例化URL对象,接着获取URL对象的输入流,再将该输入流解码成图片,最后把该图片显示出来。完整的内容如下:
package com.nan.url;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class MyURLActivity extends Activity
{
private ImageView mImageView = null;
private URL mURL = null;
private Bitmap mBitmap = null;
private InputStream mInputStream = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView)this.findViewById(R.id.img);
try {
//图片地址
mURL = new URL("http://www.android.com/images/sxsw-promo.png");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//获得URL的输入流
mInputStream = mURL.openStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//解码输入流
mBitmap = BitmapFactory.decodeStream(mInputStream);
//显示图片
mImageView.setImageBitmap(mBitmap);
try {
//关闭输入流
mInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最后,修改AndroidManifest.xml文件,加入访问网络的权限:
<uses-permission android:name="android.permission.INTERNET"/>
运行该程序: