0

我需要从网络上获取图像并将其显示在我的应用程序的主要活动中。我试图将它放在一个单独的线程中,使用以下代码(它位于 onCreate 方法中):

       Thread trd = new Thread(new Runnable(){
            @Override
            public void run(){
                ImageView iv1 = (ImageView) findViewById(R.id.promo);
                try{
                    URL url = new URL("http://www.domain.com/image.jpg");
                    InputStream content = (InputStream)url.getContent();
                    Drawable d = Drawable.createFromStream(content, "src");
                    iv1.setImageDrawable(d);
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        trd.run(); 

此代码工作正常,并使用我从网络上获取的图像更新 UI。

问题

  1. 我听说 Android 只允许您从主 UI 线程修改 UI,但看起来我的代码是从一个单独的线程中进行的。怎么会?我是否应该担心我的代码可能由于某种原因而中断?

  2. 上面的代码是否有效地确保我的应用程序 UI 在等待检索网络图像时不会冻结?

4

1 回答 1

1
I heard that Android only allows you to modify the UI from the main UI thread, but it looks like with my code I am doing it from inside a separate thread. How come? Should I be worried my code might break for some reason?

是的,您正在从一个单独的线程进行修改。

在线程使用中设置drawable,并将d其设为final。

SampleActivity.this.runOnUiThread(new Runnable() {

                    public void run() {
                        iv1.setImageDrawable(d);

                    }
                });

Is the above code efficient to make sure my app UI will not freeze while waiting for the web image to be retrieved?

No as It will not run at all. and will through the Exception.

于 2012-07-18T18:48:09.013 回答