You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native基于react-native-background-actions自定义进度条通知

React Native实现后台下载带进度条自定义通知方案

react-native-background-actions 本身没有暴露自定义通知布局的API,默认只能渲染系统基础样式通知,要实现内嵌进度条的下载提示,Android端需要做少量原生层适配,iOS端受系统限制无法实现同等效果,具体落地步骤如下:

Android端实现步骤

  • 第一步:新增自定义通知布局文件
    在项目路径 android/app/src/main/res/layout 下新建 custom_download_notification.xml,编写包含标题、进度条、进度描述的布局,代码示例:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <TextView
            android:id="@+id/notification_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:textColor="#000000"
            android:text="文件下载中"/>
        <ProgressBar
            android:id="@+id/download_progress"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:max="100"
            android:progress="0"/>
        <TextView
            android:id="@+id/notification_desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:textColor="#666666"
            android:layout_marginTop="4dp"
            android:text="准备下载..."/>
    </LinearLayout>
    
  • 第二步:修改库原生通知逻辑
    推荐使用patch-package持久化修改,避免重新安装依赖后改动丢失:
    1. 找到路径 node_modules/react-native-background-actions/android/src/main/java/com/asterinet/rnbackgroundactions/RNBackgroundActionsModule.java
    2. 在类内新增通知相关常量:
    private static final String DOWNLOAD_CHANNEL_ID = "DOWNLOAD_PROGRESS_CHANNEL";
    private static final int DOWNLOAD_NOTIFICATION_ID = 11111;
    private RemoteViews notificationLayout;
    private NotificationCompat.Builder notificationBuilder;
    
    1. 替换原有通知构建逻辑,加载自定义布局。找到原有初始化NotificationCompat.Builder的代码段,替换为如下内容,注意Android8.0以上需要先创建通知渠道:
    NotificationManager notificationManager = (NotificationManager) reactContext.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                DOWNLOAD_CHANNEL_ID,
                "下载进度通知",
                NotificationManager.IMPORTANCE_LOW
        );
        notificationManager.createNotificationChannel(channel);
    }
    
    notificationLayout = new RemoteViews(reactContext.getPackageName(), R.layout.custom_download_notification);
    notificationLayout.setTextViewText(R.id.notification_title, taskTitle);
    notificationLayout.setTextViewText(R.id.notification_desc, taskDesc);
    notificationLayout.setProgressBar(R.id.download_progress, 100, 0, false);
    
    notificationBuilder = new NotificationCompat.Builder(reactContext, DOWNLOAD_CHANNEL_ID)
            .setSmallIcon(icon)
            .setColor(color)
            .setContentIntent(pendingIntent)
            .setCustomContentView(notificationLayout)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setOngoing(true);
    
    1. 在类中新增更新通知进度的方法,添加@ReactMethod注解暴露给JS层调用:
    @ReactMethod
    public void updateDownloadProgress(int progress, String desc) {
        if (notificationManager == null || notificationLayout == null || notificationBuilder == null) return;
        notificationLayout.setTextViewText(R.id.notification_desc, desc);
        notificationLayout.setProgressBar(R.id.download_progress, 100, progress, false);
        notificationBuilder.setCustomContentView(notificationLayout);
        notificationManager.notify(DOWNLOAD_NOTIFICATION_ID, notificationBuilder.build());
    }
    
    1. 执行命令npx patch-package react-native-background-actions生成补丁包,后续安装依赖会自动应用改动。
  • 第三步:JS层对接进度更新
    后台任务启动逻辑沿用原有配置即可,在下载进度回调中调用原生暴露的方法实时刷新通知:
    import { NativeModules } from 'react-native';
    const { RNBackgroundActionsModule } = NativeModules;
    
    // 原有启动后台任务配置
    const options = {
        taskName: 'Downloading',
        taskTitle: '文件下载中',
        taskDesc: '准备下载...',
        taskIcon: {
          name: 'ic_launcher',
          type: 'mipmap',
        },
        color: '#ff00ff',
        linkingURI: 'yourSchemeHere://chat/jane',
        parameters: {
          delay: 15000,
        },
    };
    
    // 下载进度回调示例
    const handleDownloadProgress = (receivedBytes, totalBytes) => {
      const progress = Math.round((receivedBytes / totalBytes) * 100);
      const sizeText = `${(receivedBytes/1024/1024).toFixed(1)}MB/${(totalBytes/1024/1024).toFixed(1)}MB`;
      const desc = `已下载${progress}%  ${sizeText}`;
      // 调用原生方法更新通知UI
      RNBackgroundActionsModule.updateDownloadProgress(progress, desc);
    };
    

iOS端适配说明

iOS系统对后台通知自定义布局限制严格:

  • 系统原生后台下载(NSURLSession)会自动展示带进度的下载通知,不需要额外自定义
  • 若要自定义通知样式,需要新增Notification Service Extension,但该扩展仅能在通知触发时修改内容,无法做到和下载进度实时同步,业务场景下实用性极低,推荐直接使用系统默认下载提示即可。

无原生修改替代方案

如果不想改动原生代码和node_modules,可以直接替换实现方案:使用@notifee/react-native搭配下载库(如react-native-blob-util、react-native-fs)实现,notifee原生支持自定义通知布局、内嵌进度条组件,直接调用JS API即可完成进度更新,不需要手动写原生代码,适配成本更低。

内容的提问来源于stack exchange,提问作者Rover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 13:01:20