0

Webから画像を取得し、アプリのメインアクティビティに表示する必要があります。次のコードを使用して、別のスレッド内に配置しようとしています(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(); 

このコードは正しく機能しており、Webから取得した画像でUIを更新しています。

質問

  1. AndroidではメインのUIスレッドからのみUIを変更できると聞きましたが、私のコードでは別のスレッド内から変更しているようです。どうして?何らかの理由でコードが壊れるのではないかと心配する必要がありますか?

  2. 上記のコードは、Web画像が取得されるのを待っている間にアプリの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?

はい、別のスレッドから変更しています。

スレッド使用内にドローアブルを設定しd、最終的に作成します。

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?

いいえ、まったく実行されません。と意志を通じてException

于 2012-07-18T18:48:09.013 に答える