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

Firebase FCM推送安卓通知失败问题及Cloud Functions改造需求

原执行代码

import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging
from google.cloud import storage

cred = credentials.Certificate('push-notifier.json')

# Start Firebase Admin SDK
if not firebase_admin._apps:
    default_app = firebase_admin.initialize_app(cred, {
        'storageBucket': 'push-notifier-144.appspot.com'
    })
else:
    default_app = firebase_admin.get_app()

# PDF file's name and path 
local_file_path = 'Backend-TOGG.pdf'

# Crete Google Cloud Storage Connection
client = storage.Client.from_service_account_json('push-notifier-144.json')
# Choose Storage Bucket 
bucket = client.get_bucket('push-notifier-144')
# Upload the file
blob = bucket.blob('Backend-TOGG')
blob.upload_from_filename(local_file_path)

# Create the file's url
url = f'https://storage.googleapis.com/push-notifier-144.appspot.com/{blob.name}'

# Prepare the push message
message = messaging.Message(
    notification=messaging.Notification(
        title='Price Tracker Analysis has been finished.',
        body='click on here to reach analysis results.',
    ),
    data={
        'url': url
    },
    topic='price_tracker',
    android=messaging.AndroidConfig(
        ttl=86400,
        notification=messaging.AndroidNotification(
            click_action='DOWNLOAD_PDF'
        )
    )
)

# Send Push Notification
response = messaging.send(message, app=default_app)
print('Successfully sent message:', response)

问题1:为何通知未送达手机?是否需要额外配置?

通知未送达的核心原因及对应配置要求如下:

  • 设备未订阅目标主题:安卓应用端需调用FCM API完成price_tracker主题的订阅操作,未订阅的设备无法接收该主题推送。
  • 安卓应用FCM集成不完整:应用需正确集成FCM SDK,配置google-services.json文件,确保设备能成功注册FCM令牌并与Firebase项目绑定。
  • 通知权限未开启:安卓设备需为目标应用开启通知权限,部分系统的后台限制策略也会阻止应用接收推送,需确保应用在后台可正常运行。
  • Firebase项目配置缺失:需在Firebase控制台的「云消息传递」模块中,确认安卓应用的包名、SHA-1指纹已正确配置,否则推送会被系统拦截。
  • 消息处理逻辑缺失:若应用处于后台状态,部分系统对纯数据消息的展示有限制,当前代码包含notification字段属于通知消息,需确保应用端未拦截该类型消息。

问题2:无关联安卓应用时,能否通过Firebase向安卓手机发送带图标的通知?若不可行,应使用GCP的哪项服务?

无关联安卓应用时,无法通过Firebase发送带图标的通知。原因在于:
FCM推送的通知需依托安卓应用完成核心流程:设备注册FCM令牌、订阅主题,以及通知的本地展示(包括图标、通知渠道、点击行为等配置),没有关联应用的情况下,设备无法与Firebase项目建立推送关联,也无法处理通知的展示逻辑。

若要使用GCP服务实现该需求,必须先将安卓应用与Firebase项目关联;如果场景不允许关联应用,GCP没有直接的替代服务能向无应用的安卓设备发送带图标的系统通知。

问题3:改造为Storage上传触发Cloud Functions发送通知的方案

改造步骤

  1. 创建触发器:在GCP控制台创建Python类型的Cloud Functions,选择Storage触发器,事件类型为「最终创建(对象已创建)」,指定目标存储桶push-notifier-144。
  2. 配置权限:为Cloud Functions的默认服务账号添加Firebase Cloud Messaging Sender权限,确保能调用FCM API;同时授予存储桶的对象读取权限。
  3. 编写函数代码:通过事件参数获取上传文件信息,构造FCM消息并发送。

示例代码

import firebase_admin
from firebase_admin import messaging

# Cloud Functions中自动使用默认服务账号,无需手动指定证书
if not firebase_admin._apps:
    firebase_admin.initialize_app()

def on_file_uploaded(event, context):
    """Storage桶有新文件上传时触发"""
    bucket_name = event['bucket']
    file_name = event['name']
    
    # 仅处理PDF文件(可选)
    if not file_name.endswith('.pdf'):
        print('Skipping non-PDF file')
        return
    
    # 构造文件公开访问URL
    file_url = f'https://storage.googleapis.com/{bucket_name}/{file_name}'
    
    # 构造FCM推送消息
    message = messaging.Message(
        notification=messaging.Notification(
            title='Price Tracker Analysis has been finished.',
            body='Click here to view the analysis results.'
        ),
        data={'url': file_url},
        topic='price_tracker',
        android=messaging.AndroidConfig(
            ttl=86400,
            notification=messaging.AndroidNotification(
                click_action='DOWNLOAD_PDF'
            )
        )
    )
    
    # 发送通知
    response = messaging.send(message)
    print(f'Successfully sent message: {response}')

部署说明

  • 将代码保存为main.py,可通过GCP控制台或gcloud functions deploy命令部署,指定函数入口为on_file_uploaded。
  • 若需调整通知内容或过滤特定文件类型,可修改代码中的判断逻辑和消息参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:35:14