Android官方开发文档Training系列课程中文版:通知用户之在通知中显示进度
原文地址:http://android.xsoftlab.net/training/notify-user/display-progress.html#FixedProgress
通知中包含了一個進度指示器,用來向用戶展示一項正在進行中的工作狀態。如果你可以確保任務會花費多長時間,并且可以在任何時候得知它完成了多少工作,那么就可以使用確定樣式的指示器(一個進度條)。如果不能確定任務需要花費的時間,可以使用不確定樣式的指示器(一個活動的指示器)。
進度指示器由ProgressBar類實現。
使用進度指示器,可以調用setProgress()方法。確定樣式與不確定樣式會在下面的章節中討論。
顯示確定進度指示器
為了顯示確定進度指示器,需要調用setProgress(max, progress, false)方法將指示器添加到通知上,然后再將該通知發布出去。該方法的第三個參數用于指示該進度條是確定性進度條(true)還是不確定性進度條(false)。隨著操作的處理,進度progress會增長,這時需要更新通知。在操作結束時,progress應該等于max。一種常規的方式是將max設置為100,然后將progress以百分比的形式自增。
你也可以選擇在任務完成的時候將進度條取消顯示或者移除通知。在前一種情況中,要記得更新通知的文本,告訴用戶任務已完成。后一種情況中,調用setProgress(0, 0, false)就可以完成通知的移除。
int id = 1; ... 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() {@Overridepublic void run() {int incr;// Do the "lengthy" operation 20 timesfor (incr = 0; incr <= 100; incr+=5) {// Sets the progress indicator to a max value, the// current completion percentage, and "determinate"// statemBuilder.setProgress(100, incr, false);// Displays the progress bar for the first time.mNotifyManager.notify(id, mBuilder.build());// Sleeps the thread, simulating an operation// that takes timetry {// Sleep for 5 secondsThread.sleep(5*1000);} catch (InterruptedException e) {Log.d(TAG, "sleep failure");}}// When the loop is finished, updates the notificationmBuilder.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, true)方法將進度條顯示在通知中,然后將該通知發布。第一第二個參數將會被忽略,第三個參數決定了該進度條是否是不確定性進度條。最終的顯示效果為與常規進度條有相同的顯示風格,除了它一直在動之外。
在操作開始之前請發布該通知,進度動畫會一直持續運行,直到你修改了通知。當操作完成后,調用setProgress(0, 0, false)方法然后更新通知以便移除活動指示器。否則的話,就算是任務完成后,該動畫也不會停止。所以要記得在任務完成后更改通知文本,以便告知用戶操作已完成。
// Sets the progress indicator to a max value, the current completion // percentage, and "determinate" state mBuilder.setProgress(100, incr, false); // Issues the notification mNotifyManager.notify(id, mBuilder.build());找到前面的代碼,將下面部分替換。要記得setProgress()方法的第三個參數為true:
// Sets an activity indicator for an operation of indeterminate length mBuilder.setProgress(0, 0, true); // Issues the notification mNotifyManager.notify(id, mBuilder.build());最終的顯示效果如下:
總結
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:通知用户之在通知中显示进度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅谈事理图谱认知:系统体系+领域收敛+人
- 下一篇: Android UI之困 横跨四个屏幕的