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

Java Web应用用FCM推通知报错:找不到Notification.builder()方法

解决FCM推送中Notification.builder()编译错误的方案

你遇到的编译错误:

Uncompilable code - cannot find symbol symbol: method builder()
location: class com.google.firebase.messaging.Notification

核心原因是Firebase Admin SDK版本过低(Notification.builder()方法在较新版本SDK中才引入),或者导入了错误的Notification类。以下是具体解决步骤:

1. 升级Firebase Admin SDK依赖

确保项目使用最新稳定版的firebase-admin依赖,旧版本没有Notification.builder()方法:

  • Maven项目(pom.xml):
<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>22.0.0</version>
</dependency>
  • Gradle项目(build.gradle):
implementation 'com.google.firebase:firebase-admin:22.0.0'

2. 确认导入正确的Notification类

检查代码顶部的导入语句,必须是Firebase Messaging的Notification类,不要导入Android SDK或其他无关包的Notification:

import com.google.firebase.messaging.Notification;

3. 清理编译缓存

更新依赖后如果仍报错,执行项目构建工具的清理命令,清除旧编译缓存:

  • Maven:mvn clean install
  • Gradle:./gradlew clean build

修正后的完整代码

确保依赖和导入正确后,你的代码可正常运行(优化了变量名以符合规范):

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FirebaseMessagingSnippets {

    public final static String registrationToken = "token";
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    public static void sendAll() throws FirebaseMessagingException, FileNotFoundException, IOException {

        FileInputStream serviceAccount = new FileInputStream("service.json");

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .build();

        FirebaseApp.initializeApp(options);

        Message message = Message.builder()
                .setNotification(Notification.builder()
                        .setTitle("Price drop")
                        .setBody("2% off all books")
                        .build())
                .putData("title", "850")
                .putData("body", "2:45")
                .setToken(registrationToken)
                .build();

        String response = FirebaseMessaging.getInstance().send(message);
        System.out.println("Successfully sent message: " + response);
    }
}

内容的提问来源于stack exchange,提问作者Shekhar J. Lobo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:35:30