使用带有Java的Firebase云向单个设备发送消息

时间:2018-03-28 11:54:13

标签: java firebase firebase-cloud-messaging

我正在尝试使用Java应用程序中的令牌向单个设备发送消息。我正在使用Firebase Admin SDK。以下是我的内容

    FileInputStream serviceAccount = null;
    try {
        serviceAccount = new FileInputStream("google-services.json");
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
    }

    FirebaseOptions options = null;
    try {
        options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://MYPROJECTID.firebaseio.com/")
            .build();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    FirebaseApp.initializeApp(options);

    String registrationToken = "MYDEVICETOKEN";

    // See documentation on defining a message payload.
    Message message = Message.builder().putData("time", "2:45").setToken(registrationToken)
            .build();

    // Send a message to the device corresponding to the provided
    // registration token.
    String response = null;
    try {
        response = FirebaseMessaging.getInstance().sendAsync(message).get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    // Response is a message ID string.
    System.out.println("Successfully sent message: " + response);

但我得到以下异常

java.io.IOException: Error reading credentials from stream, 'type' field not specified.

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

错误表示您的google-services.json文件包含无效数据。 GoogleCredentials类要求您的文件具有type属性,但它不存在。

简短的谷歌搜索给了我关于非常类似问题的this帖子。它说:

  

从API管理器中,只需创建选择"创建凭据" >   "服务帐户密钥"并为服务生成新密钥   与您的Google Play帐户相关联。

答案 1 :(得分:0)

单击生成新私钥按钮。 console snapshot

相关问题