Activity.runOnUiThread 和 View.post()的讲解

来源:互联网 发布:懒人js 编辑:程序博客网 时间:2024/04/28 01:12

public class MainActivity extends Activity {

Button button;ImageView imageView;Context context;Runnable runnable;Bitmap bitmap;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    context=this;    //初始化控件    init();    //控件点击事件    weightOnClick();}private void init(){    button= (Button) findViewById(R.id.bt_download);    imageView= (ImageView) findViewById(R.id.image);    runnable=new Runnable() {        @Override        public void run() {            if (bitmap!=null){                imageView.setImageBitmap(bitmap);            }        }    };}private void weightOnClick(){    button.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View v) {            new Thread(new Runnable() {                @Override                public void run() {                    HttpURLConnection httpURLConnection=null;                    InputStream inputStream=null;                    try {                        URL url=new URL("http://c.hiphotos.baidu.com/image/pic/item                        /c8ea15ce36d3d53984cf1e113e87e950342ab075.jpg");                        httpURLConnection= (HttpURLConnection) url.openConnection();                         inputStream=httpURLConnection.getInputStream();                        bitmap= BitmapFactory.decodeStream(inputStream);                       // ((Activity)context).runOnUiThread(runnable);                        imageView.post(runnable);                        inputStream.close();                    } catch (Exception e) {                        e.printStackTrace();                    }finally {                        httpURLConnection.disconnect();                    }                }            }).start();        }    });}

}

1 0