set FCM high-priority when using firebase-admin
Asked Answered
P

4

6

I have the following code which uses firebase-admin to send messages using Firebase cloud messaging

Message message = null;
message = Message.builder().putData("From", fromTel).putData("To", toTel).putData("Text", text)
            .setToken(registrationToken).build();

String response = null;
try {
    response = FirebaseMessaging.getInstance().sendAsync(message).get();
    responseEntity = new ResponseEntity<String>(HttpStatus.ACCEPTED);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}
System.out.println("Successfully sent message: " + response);

The above code works fine. But I need to send "high-priority" messages so that the device can receive them while in doze mode.

How can I make the messages "high-priority"?

Proudlove answered 1/4, 2018 at 19:25 Comment(0)
S
6

For sending to Android devices, when building the message, set its AndroidConfig to a value that has Priority.HIGH:

AndroidConfig config = AndroidConfig.builder()
        .setPriority(AndroidConfig.Priority.HIGH).build();

Message message = null;
message = Message.builder()
        .putData("From", fromTel).putData("To", toTel).putData("Text", text)
        .setAndroidConfig(config) // <= ADDED
        .setToken(registrationToken).build();

For additional details, see the example in the documentation.

When sending to Apple devices, use setApnsConfig(), as explained in the documentation.

Sympathize answered 1/4, 2018 at 20:34 Comment(7)
Thanks for the answer. The high priority is working, but still if I don't touch my phone for a while, and when I send it a Firebase cloud message it takes the phone a very long time to process it. Am I supposed to using Firebase Job Dispatcher in order for my app to work when the phone is sleep? When the phone is awake the phone processes everything within a few secondsProudlove
With a high-priority message, I would expect the message receipt delay to be about the same for an awake and sleeping device. What model phone are you testing with? I have seen reports of different behaviors depending on device model.Sympathize
It's running on the Moto G4 PlayProudlove
You could try sending notifications from the Firebase Console. The are high-priority by default and will give you an idea of receipt delay for different device states.Sympathize
I did some debugging, I now print something on the app screen with a timestamp when a Firebase message is received. The message does appear, but it does not continue to do rest of the job. It's supposed to create a new instance of a class, then create a new thread and download an image. This is the class that it will use once a Firebase message is received pastebin.com/RUrZwb4L I'm not sure if I'm doing something wrong on my sideProudlove
SO is not an efficient forum for debugging. I would expect an awakened device to remain awake for at least 10 seconds. Maybe the image download is taking longer than expected. You're making good use of log-statements. Add more if needed to determine if the device is going to sleep before the processing is complete.Sympathize
I will try to figure it out with more debugging, but I think the issue is the phone. I'm going to try it with a different ROM to see what happensProudlove
N
3

Without an AndroidConfig Builder

function sendFCM(token, from, to, text) {
    var admin = require("firebase-admin");
    var data = {
        from: from,
        to: to,
        text: text
    };
    let message = {       
        data: data,
        token: token,
        android: {
            priority: "high",  // Here goes priority
            ttl: 10 * 60 * 1000, // Time to live
        }
    };
    admin.messaging()
        .send(message)
        .then((response) => {
            // Do something with response
        }).catch((error) => {
            console.log(error);
        });
}
Nadler answered 1/3, 2021 at 23:42 Comment(0)
W
2
public async Task send_PushNotification(FirebaseAdmin.Messaging.Message MESSAGE)
    {   
        var defaultApp = FirebaseApp.Create(new AppOptions()
        {
            Credential = GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "key_FB.json")),
        });

        var message = MESSAGE;
        message.Token = FB_TOKEN;
        message.Android = new AndroidConfig();
        message.Android.Priority = Priority.High;
        message.Android.TimeToLive = new TimeSpan(0,0,5);
       
        var messaging = FirebaseMessaging.DefaultInstance;
        var result = await messaging.SendAsync(message);
        Console.WriteLine(result);
    }
Wunderlich answered 17/12, 2020 at 20:29 Comment(1)
Please provide more explanation to your answer, e.g. putting it in the context of a question.Curve
S
1

This may help somebody.

public String sendFcmNotification(PushNotificationRequestDto notifyRequest) throws FirebaseMessagingException {
        String registrationToken = notifyRequest.getToken();

        AndroidConfig config = AndroidConfig.builder()
                .setPriority(AndroidConfig.Priority.HIGH).build();

        Notification notification = Notification.builder()
                .setTitle(notifyRequest.getTitle())
                .setBody(notifyRequest.getBody())
                .build();

        Message message = Message.builder()
                .setNotification(notification)
//                .putData("foo", "bar")
                .setAndroidConfig(config)
                .setToken(registrationToken)
                .build();


        return FirebaseMessaging.getInstance().send(message);
    }
Skipper answered 28/7, 2020 at 6:19 Comment(1)
Worked nicely! Thanks.Towhee

© 2022 - 2024 — McMap. All rights reserved.