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.
great example, helped me a lot. many thanks. but the line
ReplyDeleteprogressDialog.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
Hello Iiasa Laxenburg,
ReplyDeleteThanks for your comment.