• 使用URL读取网络图片资源


    URL(Uniform Resource Locator) 对象代表统一资源定位器。

    代码如下:

    public class MainActivity extends ActionBarActivity {
        private ImageView image;
        //从网络下载得到的图片
        Bitmap bitmap;
        Handler handler = new Handler(){
    
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == 0x123){
                    image.setImageBitmap(bitmap);
                }
                
            }
            
        };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            image = (ImageView)this.findViewById(R.id.show);
            //开启新线程,新线程中不能直接修改UI控件的内容。
            new Thread(){
    
                @Override
                public void run() {
                    try {
                        //定义URL对象,给出URL地址
                        URL url = new URL("http://www.duducat.com/home/upload/14477558734.jpg");
                        //打开URL对应的资源的输入流
                        InputStream is = url.openStream();
                        //从InputStream中解析出图片
                        bitmap = BitmapFactory.decodeStream(is);
                        //发送消息,通知UI组件显示该图片
                        handler.sendEmptyMessage(0x123);
                        is.close();
                        //再次打开URL对应的资源输入流
                        is = url.openStream();
                        //打开手机文件对应的输入流
                        OutputStream os = openFileOutput("14477558734.jpg", 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) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                
                }
                
            }.start();
        }

    千万别忘了在AndroidManifest.xml文件中授予网络的权限。

    <uses-permission android:name="android.permission.INTERNET"/>
  • 相关阅读:
    K&R C C90,C99的改进
    Windows 用来定位 DLL 的搜索路径
    常量字符串的问题
    C++0x中一些有用的新特性
    mainfest机制
    mainfest机制
    C++0x中一些有用的新特性
    c语言目标程序中的段
    c语言目标程序中的段
    数据模型(LP32 ILP32 LP64 LLP64 ILP64 )
  • 原文地址:https://www.cnblogs.com/prescheng/p/4986259.html
Copyright © 2020-2023  润新知