Android中使用可以控制状态(开始、暂停、停止)的 ProgressBar

代码与范例:

// 通过类 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 的线程的运行状态。一个可以暂停与中断的进度条在有些情况下是很必要的。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注