首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 後台下載圖片並通過 Notification 提示進度與結果

     編輯:程式設計疑難解答

需求場景

類似百度音樂:後台下載圖片,通知欄顯示進度條,下載完成點擊通知打開圖片或提示用戶。

核心組件

  1. Service:承載下載任務,確保進程存活。推薦 IntentService 或 Foreground Service(Android 8.0+ 必須)。
  2. NotificationCompat.Builder:構建帶進度條的通知,setProgress(max, progress, false) 動態更新。
  3. DownloadManager / OkHttp / HttpURLConnection:實際下載邏輯,支持斷點續傳更佳。

關鍵步驟

// 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 下載鏈接

注意事項

  • Android 8.0+ 必須創建 NotificationChannel。
  • 大文件建議使用 DownloadManager 系統服務,自動處理網絡切換、斷點續傳。
  • 存儲路徑優先使用 getExternalFilesDir(Environment.DIRECTORY_PICTURES),無需權限。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved