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を更新しています。
質問:
AndroidではメインのUIスレッドからのみUIを変更できると聞きましたが、私のコードでは別のスレッド内から変更しているようです。どうして?何らかの理由でコードが壊れるのではないかと心配する必要がありますか?
上記のコードは、Web画像が取得されるのを待っている間にアプリのUIがフリーズしないようにするために効率的ですか?