您的位置:首页 > 理论基础 > 计算机网络

初学Android,网络应用之访问网络资源(八十六)

2012-11-12 17:06 405 查看
下面程序读取CSDN的logo图片



public class URLTest extends Activity
{
	ImageView show;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		show = (ImageView) findViewById(R.id.show);
		// 定义一个URL对象
		try
		{
			URL url = new URL("http://csdnimg.cn/www/images/csdnindex_logo.gif");
			// 打开该URL对应的资源的输入流
			InputStream is = url.openStream();
			// 从InputStream中解析出图片
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			// 使用ImageView显示该图片
			show.setImageBitmap(bitmap);
			is.close();
			// 再次打开URL对应的资源的输入流
			is = url.openStream();
			// 打开手机文件对应的输出流
			OutputStream os = openFileOutput("csdnindex_logo.gif"
				, MODE_WORLD_READABLE);
			byte[] buff = new byte[1024];
			int hasRead = 0;
			// 将URL对应的资源下载到本地
			while((hasRead = is.read(buff)) > 0)
			{
				os.write(buff, 0 , hasRead);
			}
			is.close();
			os.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: