如何使用处理程序运行图像

时间:2013-08-28 03:15:42

标签: android image stream handler runnable

我是新手,我有一个问题,我想用函数处理程序运行图像,但我失败了, 喜欢在这段代码上运行图像的代码是什么?可以帮我解决这个问题吗?

Intent intent = getIntent();

 String url= intent.getStringExtra("URL");
tombol2 = (Button) findViewById(R.id.button2);

iv = (ImageView) findViewById(R.id.imageView1);
Drawable d1=LoadImageFromWebOperations(url);
iv.setImageDrawable(d1);

}
private Drawable LoadImageFromWebOperations(String url)
        {
             try
             {
                 InputStream is = (InputStream) new URL(url).getContent();
                 Drawable d = Drawable.createFromStream(is, "src name");
                 return d;
        }catch (Exception e) {
                 System.out.println("Exc="+e);
                 return null;
             }  
        }
   }

2 个答案:

答案 0 :(得分:0)

如果您想使用Handler,请使用如下所示。

但是我看到你在ui线程上进行与网络相关的操作,这在蜂窝后是不可能的。您必须使用线程或asynctask。您将获得NetworkOnMainThreadException

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

我建议您使用threadAsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html

Handler m_handler;
Runnable m_handlerTask ;  
m_handler = new Handler();   
m_handlerTask = new Runnable()
{
  @Override 
  public void run() { 

    // do something  
    m_handler.postDelayed(m_handlerTask, 1000);    

  }
  };
 m_handlerTask.run();

答案 1 :(得分:0)

它已修复,只需在LoadImageWebOperations

之前提供此runnable
runnable = new Runnable() {

        @Override
        public void run() {
            try {
                LoadImageFromWebOperations(d1);
            } catch (Exception e) {
                e.getStackTrace();
            }
            new Handler().postDelayed(runnable, 10000);
        }
    };
    new Handler().postDelayed(runnable, 10000);     
}