only the original thread that created a view

本来准备写一个简单的通过url获取网络图片setimage到imageview上去

没想到还是有一些小bug

先把源码供上

package com.example.seturlbitmapdemo;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {

    protected static final int COMPLETED = 0;
    Bitmap bitmap;
    String url = "http://192.168.1.164/Upload_Files/262/339/201507/5582e259-9e70-478c-91b9-1f787fa11c77.jpg";
    private ImageView iv;
    private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            if (msg.what == COMPLETED) {  
                iv.setImageBitmap(bitmap);
            }  
        }  
    }; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.imageView1);

        getPic(iv,url);

    }

    private void getPic(final ImageView iv,final String url) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url)
                            .openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);                    
                    is.close();

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Message msg = new Message();  
                msg.what = COMPLETED;  
                handler.sendMessage(msg);  
            }
        }).start();
    }

}

xml布局就是一个imageview

我一只告诉自己要用主线程更新ui
我在子线程里面获取数据,用一个handler接受获取数据成功的回调信息msg,然后更新ui,把bitmap设为全局的变量,这样就对了。

你可能感兴趣的:(android,socket通信,android,网络通信,android,开发中监测到并解决了的bug)