简介:

访问一个网络上的图片,设置在ImageView上显示,并下载到本地


范例效果:



范例代码:

acitivity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><ImageView  android:id="@+id/show"android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="fitCenter"/></LinearLayout>

MainActivity:

public class URLTest extends Activity{ImageView mImageView;// 代表从网络下载得到的图片Bitmap mBitmap;Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg){if(msg.what == 0x123){// 使用ImageView显示该图片mImageView.setImageBitmap(mBitmap);}}};@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);mImageView = (ImageView) findViewById(R.id.show);new Thread(){public void run(){try{// 定义一个URL对象URL url = new URL("http://n.sinaimg.cn/transform/20150709/gf4o-fxewnih2154047.png");// 打开该URL对应的资源的输入流InputStream is = url.openStream();// 从InputStream中解析出图片mBitmap = BitmapFactory.decodeStream(is);// 发送消息、通知UI组件显示该图片handler.sendEmptyMessage(0x123);is.close();// 再次打开URL对应的资源的输入流is = url.openStream();// 打开手机文件对应的输出流OutputStream os = openFileOutput("crazyit.png", 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();}}}.start();}}

更多相关文章

  1. Qt 打开安卓相册选择图片并获取图片的本地路径
  2. Android(安卓)时间选择器(TimeBucketSelector)
  3. Android(安卓)Studio---创建java项目
  4. Android(安卓)图片平铺实现方式
  5. Android之kotlin里面本地图片BitmapFactory.decodeFile转bitmap
  6. [IMX6Q][Android6.0.1_r3]之系统屏幕显示默认设置更改
  7. Google Map无法显示:Error contacting Google servers. XXX authe
  8. Android(安卓)整理常用的第三方库
  9. android webview 介绍

随机推荐

  1. android 上网 (一)-- apn切换拨号
  2. Android(安卓)Scroller的使用及自我理解
  3. 把手机变成鼠标和触摸板,附android/iphone
  4. Android学习之 那些让我生疏的配置属性
  5. Android中新建的文件在R没有显示对应的文
  6. Galaxy S II vs HTC Sensation XE vs 小
  7. android正在运行进程和后台缓存进程的区
  8. Android开发者选项中,这29个功能你忽略了
  9. Android用户权限之记录是否调起弹窗
  10. Android(安卓)Architecture Components(六