Saturday, July 16, 2011

ProgressDialog + Thread

In this exercise, we will be implementing a background Thread. When the app start, a ProgressDialog will be shown, and a Thread will be start. When the thread finished in 10 seconds, it will generate a handler message to dismiss the ProgressDialog.

ProgressDialog.show()
progressDialog.dismiss()


package com.exercise.AndroidProgressDialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class AndroidProgressDialogActivity extends Activity {

ProgressDialog progressDialog;
BackgroundThread backgroundThread;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      progressDialog = ProgressDialog.show(AndroidProgressDialogActivity.this,
              "ProgressDialog", "Wait!");
    
      backgroundThread = new BackgroundThread();
      backgroundThread.setRunning(true);
      backgroundThread.start();
  }



  public class BackgroundThread extends Thread{
   volatile boolean running = false;
   int cnt;
  
   void setRunning(boolean b){
    running = b;
    cnt = 10;
   }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(running){
   try {
    sleep(1000);
    if(cnt-- == 0){
     running = false;
    }
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  handler.sendMessage(handler.obtainMessage());
 }
  }

  Handler handler = new Handler(){

 @Override
 public void handleMessage(Message msg) {
  // TODO Auto-generated method stub
  progressDialog.dismiss();

  boolean retry = true;
  while(retry){
   try {
    backgroundThread.join();
    retry = false;
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 
  Toast.makeText(AndroidProgressDialogActivity.this,
    "dismissed", Toast.LENGTH_LONG).show();
 }
  
  };
}


next:
- Display a indeterminate progress bar on title bar

Remark:
progressDialog.dismiss(); 
must be in a try/catch block. otherwise the app crashes if you rotate (landscape/portrait) the device during running of the BackgroundThread. 
~ thanks Iiasa Laxenburg's comments.

2 comments:

Iiasa Laxenburg said...

great example, helped me a lot. many thanks. but the line
progressDialog.dismiss();
must be in a try/catch block. otherwise the app crashes if you rotate (landscape/portrait) the device during running of the BackgroundThread. // hans

Andr.oid Eric said...

Hello Iiasa Laxenburg,

Thanks for your comment.