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"/>