david
david

Reputation: 1077

send message to single device using Firebase cloud with Java

I'm trying to send messages to single devices using their token from a Java application. I'm using the Firebase Admin SDK. Below is what I have

    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);

But I get the following exception

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

What am I doing wrong here?

Upvotes: 2

Views: 1826

Answers (2)

xbranko
xbranko

Reputation: 663

Click on Generate new private key button. console snapshot

Upvotes: 2

Aleksei Budiak
Aleksei Budiak

Reputation: 921

The error means that your google-services.json file contains invalid data. GoogleCredentials class expects your file to have a type property, but it's not there.

Brief googling gave me this post regarding very similar problem. It says:

From the API Manager, just create select "Create credentials" > "Service Account key" and generate a new key for the Service that is associated to your Google Play account.

Upvotes: 1

Related Questions