如何在本地通知(Local Notification)中添加进度视图(Progress view)?
当然可以!不过得看你用的是iOS还是Android平台,我分别给你拆解下实现方式:
iOS 实现方案
从iOS 10开始,苹果的UserNotifications框架就支持在本地通知中添加进度视图了,刚好能满足你展示上传进度的需求:
- 你可以通过
UNMutableNotificationContent的progress属性设置进度值(范围是0.0到1.0,对应0%到100%);如果是上传准备阶段,还能把isIndeterminate设为true,显示不确定的加载动画。 - 举个Swift的简单实现示例:
import UserNotifications // 创建通知内容 let content = UNMutableNotificationContent() content.title = "上传进度" content.body = "正在上传文件..." // 设置当前完成60%的进度 content.progress = 0.6 content.isIndeterminate = false // 创建通知请求,用唯一标识来后续更新 let request = UNNotificationRequest(identifier: "uploadProgressNotification", content: content, trigger: nil) // 添加通知到系统 UNUserNotificationCenter.current().add(request) { error in if let error = error { print("添加进度通知失败: \(error.localizedDescription)") } }
- 实时更新进度的话,只需要用同一个
identifier重新创建带有新进度值的通知请求并添加即可,系统会自动替换旧通知。如果上传任务在后台运行,记得申请对应的后台权限(比如Background Processing),保证进度能及时更新。
Android 实现方案
Android从API 26(Oreo版本)开始,通知系统支持内置进度条,适配起来也很方便:
- 使用
NotificationCompat.Builder的setProgress()方法配置进度:第一个参数是进度最大值(通常设为100代表百分比),第二个是当前完成进度,第三个参数设为true时显示不确定加载动画,false时显示确定进度。 - 举个Kotlin的实现示例:
import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.core.app.NotificationCompat // 先创建通知渠道(API 26+必须) private fun createUploadChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( "upload_progress_channel", "上传进度通知", NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "展示文件上传进度的通知" } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } // 显示/更新上传进度通知 fun updateUploadProgress(context: Context, currentProgress: Int) { createUploadChannel(context) val notificationBuilder = NotificationCompat.Builder(context, "upload_progress_channel") .setSmallIcon(R.drawable.ic_upload_icon) .setContentTitle("文件上传中") .setContentText("当前进度: $currentProgress%") .setPriority(NotificationCompat.PRIORITY_DEFAULT) // 设置进度:最大值100,当前进度currentProgress,非不确定模式 .setProgress(100, currentProgress, false) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // 用同一个通知ID更新通知 notificationManager.notify(1001, notificationBuilder.build()) }
- 上传过程中,定期调用
updateUploadProgress()传入最新进度值就行。如果是后台上传任务,Android 8.0+需要使用前台服务(Foreground Service),避免通知被系统回收,同时要注意适配不同版本的后台限制政策。
内容的提问来源于stack exchange,提问作者Sudha
相关产品推荐
相关产品推荐

