- 对于可以知道确切进度的操作,使用“确定”形式的进度指示条
- 对于不确切知道进度的,使用不确定形式的指示条
- 进度条基于平台的ProgressBar类实现
- 使用进度条:
> 4.0及以后的版本:setProgress()
> 早期版本:需要自定义通知布局,其中包含ProgressBar视图
显示一个固定周期进度显示器
- 调用
setProgress(max, progress, false)来设置通知
- 通常将max设置为100,progress设置为操作完成进度的百分点
- 可以选择在操作完成之后仍然显示进度条,或者移除它。无论哪种形式,记得更新通知的文字以显示操作已经完成。要移除进度条,调用
setProgress(0, 0, false)
...
mNotifyManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_notification);
// Start a lengthy operation in a background thread
new Thread(
new Runnable() {
@Override
public void run() {
int incr;
// Do the "lengthy" operation 20 times
for (incr = 0; incr <= 100; incr+=5) {
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
mBuilder.setProgress(100, incr, false);
// Displays the progress bar for the first time.
mNotifyManager.notify(0, mBuilder.build());
// Sleeps the thread, simulating an operation
// that takes time
try {
// Sleep for 5 seconds
Thread.sleep(5*1000);
} catch (InterruptedException e) {
Log.d(TAG, "sleep failure");
}
}
// When the loop is finished, updates the notification
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0,0,false);
mNotifyManager.notify(ID, mBuilder.build());
}
}
// Starts the thread by calling the run() method in its Runnable
).start();
- 效果:
显示一个持续活动指示器
- 这是在处理进度无法准确获知时显示活动正在持续
- 在所有操作开始之前发出通知。操作持续的动画将一直显示直到你修改你的通知。
- 操作结束时,调用
setProgress(0, 0, false)
并更新通知以移除指示条
- 将上段代码中相关设置替换为:
// Sets an activity indicator for an operation of indeterminate length
mBuilder.setProgress(0, 0, true);
// Issues the notification
mNotifyManager.notify(0, mBuilder.build());
- 效果: