類似百度音樂:後台下載圖片,通知欄顯示進度條,下載完成點擊通知打開圖片或提示用戶。
IntentService 或 Foreground Service(Android 8.0+ 必須)。setProgress(max, progress, false) 動態更新。// 1. 創建前台服務通知
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("圖片下載中")
.setContentText("0%")
.setSmallIcon(R.drawable.ic_download)
.setProgress(100, 0, false)
.build();
startForeground(NOTIFY_ID, notification);
// 2. 下載循環中更新進度
int progress = (int) (downloaded * 100 / total);
notification.contentView.setProgressBar(R.id.progress_bar, 100, progress, false);
notification.contentView.setTextViewText(R.id.tv_progress, progress + "%");
notificationManager.notify(NOTIFY_ID, notification);
// 3. 完成後更新通知為可點擊意圖
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "image/*");
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("下載完成")
.setContentText("點擊查看")
.setSmallIcon(R.drawable.ic_done)
.setContentIntent(pi)
.setAutoCancel(true)
.build();
notificationManager.notify(NOTIFY_ID, notification);
stopForeground(true);
完整項目示例:CSDN 下載鏈接
NotificationChannel。DownloadManager 系統服務,自動處理網絡切換、斷點續傳。getExternalFilesDir(Environment.DIRECTORY_PICTURES),無需權限。