读取网络图片

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ImageView iv = (ImageView) findViewById(R.id.imageView);
            if (msg.what == 1) {
                iv.setImageBitmap((Bitmap) msg.obj);
            }
        }
    };
    public void click(View view) throws Exception {
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://123.56.111.226:8080/tomcat.gif");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        Message message = new Message();
                        message.what = 1;
                        message.obj = bitmap;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

 

posted @ 2015-11-04 13:20  一路向北中  阅读(170)  评论(0)    收藏  举报