Android:下载网络图片

LoadImageThread.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class LoadImageThread extends Thread {

    private String url;
    private ImageView imageView;

    public LoadImageThread(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    @Override
    public void run() {
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setConnectTimeout(5000);//超时等待
            connection.setRequestMethod("GET");//访问方式
            InputStream in = connection.getInputStream();

            FileOutputStream out = null;
            File downloadFile = null;
            String fileName = String.valueOf(System.currentTimeMillis()) + url.substring(url.lastIndexOf("."));//保存名称

            //判断ID卡是否存在
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File parent = Environment.getExternalStorageDirectory();//获取ID卡目录
                downloadFile = new File(parent, fileName);
                out = new FileOutputStream(downloadFile);
            }
            if (out != null) {
                //创建缓冲区
                byte[] b = new byte[2 * 1024];
                int len;

                //下载图片到本地
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }

                //创建Bitmap
                final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
                imageView.post(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);

        new LoadImageThread("http://pic1.sc.chinaz.com/files/pic/pic9/201509/apic15021.jpg"
                , imageView).start();   
    }   
}

AndroidManifest.xml




参考:http://www.imooc.com/video/7213

你可能感兴趣的:(android,Android_Network,Android_Image)