代码与范例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
// 通过类 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(); } } |
说明:可以通过一个辅助类来方便地改变控制 ProgressBar 的线程的运行状态。一个可以暂停与中断的进度条在有些情况下是很必要的。