Thursday 7 October 2010

Andoid: Change progress in progress dialog from the different thread

We should use Handler that allows you to send message to the thread

  private int increment;
  private ProgressDialog m_ProgressDialog; 
  public void onCreate(Bundle savedInstanceState) {

    Runnable viewImages = new Runnable(){
    @Override
      public void run() {
        getImages();
      }
    };
  
    m_ProgressDialog = new ProgressDialog(this);
    m_ProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    m_ProgressDialog.setMessage("Loading...");
    m_ProgressDialog.show();

   Thread thread =  new Thread(null, viewImages, "MagentoBackground");
   thread.start();
}

  //obtain message from thred
  Handler progressHandler = new Handler() {
      public void handleMessage(Message msg) {
           m_ProgressDialog.incrementProgressBy(increment);
      }
  };

  private void getImages(){
    try{
    //do smth, load image for example, in may be cycle
    increment = 100/ images.size();
    progressHandler.sendMessage(progressHandler.obtainMessage());  //send message
    Thread.sleep(2000);
    } catch (Exception e) {
         Log.e("BACKGROUND_PROC", e.getMessage());
    }
  }

No comments:

Post a Comment