网络获取图片



 private Bitmap bitmap;



   @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_glide);
        img = findViewById(R.id.iamge);
        img2 = findViewById(R.id.iamge2);
        img3 = findViewById(R.id.image3);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    httpUrlConnectionImage();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }).start();
}

    android.os.Handler handler = new android.os.Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            img.setImageBitmap(bitmap);
        }
    };

 private void httpUrlConnectionImage() throws MalformedURLException {
        URL url = new URL("http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg");
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
            handler.sendEmptyMessage(2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(网络获取图片)