// 通过类 ProgressBarUpdater 来控制线程的运行状态
public class ProgressBarUpdater implements Runnable {
private volatile boolean paused = true;
private volatile boolean finished = false;
public void run() {
while (!finished) {
// wait
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
}
if (!paused) {
// Update the progress status
ProgressStatus = doWork();
progressBar.setProgress(ProgressStatus);
}
while (paused && !finished) {
// wait
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}
public synchronized void pauseProgressBar() {
paused = true;
}
public synchronized void unPauseProgressBar() {
paused = false;
// call notify() here when you switch to wait/notify.
}
public void stopProgressBar() {
finished = true;
// call notify() here too.
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setTitle(getResources().getString(R.string.number));
ProgressStatus = 0;
Button1 = (Button) this.findViewById(R.id.button1);
Button1.setOnClickListener(this);
Button2 = (Button) this.findViewById(R.id.button2);
Button2.setOnClickListener(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setMax(100);
progressBar.setProgress(0);
// progressBar.setSecondaryProgress(70);
// 使用 ProgressBarUpdater 来构造新的线程
ProgressBarUpdater pbu = new ProgressBarUpdater();
Thread t = new Thread(pbu);
t.start();
pbu.pauseProgressBar();
}
// 通过 ProgressBarUpdater 来控制进度条的运行状态
@Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
pbu.unPauseProgressBar();
}
if (v.getId() == R.id.button2) {
pbu.pauseProgressBar();
}
}