How to Send Notification to Specific Users with Fcm

How to send notification to specific users with FCM?

Did I need to create a web server

Yes. You need a place where you can map name/email to registration IDs. These registration IDs must be included in the request to FCM, for example

{
'registration_ids': ['qrgqry34562456', '245346236ef'],
'notification': {
'body': '',
'title': ''
},
'data': {

}
}

will send the push to 'qrgqry34562456' and '245346236ef'.

The registration ID you use in the call is the one that's called 'token' in this callback in the app.

public class MyService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
}
}

Can I Send notifications to specific users in firebase cloud messaging console

You can send notifications from the console to specific users by following the steps below:

  1. Get the FCM registration tokens for the users' devices. You can check how to get the tokens for the devices depending on the platform here.
  2. Go to the project's Notification Composer.
  3. Enter the notification details i.e notification title(optional),
    notification text, notification image(optional), notification name(optional)
    .
  4. Click Send test message.
  5. Enter the FCM registration tokens.
  6. Click Test.

Send notification to specific user firebase in flutter

The above solution works, however, my solution is much simpler, and avoids adding new technologies

I have figured out how send a notification to another device using an in app feature.

First, you will need to import the necessary packages:

firebase_messaging

flutter_local_notifications

Note: you will also use the http package

Also note: to send notifications to another device, you must know the device token of that device. I prefer getting the token and saving it in Firestore or Realtime Database. Here is the code to get the device token.

String? mtoken = " ";

void getToken() async {
await FirebaseMessaging.instance.getToken().then((token) {
setState(() {
mtoken = token;
});
});
}

The token will be saved in mtoken, you can now use this as the token for the coming steps.

The next step is to request permission to send push notifications to your app.

  void requestPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;

NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);

if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
} else if (settings.authorizationStatus ==
AuthorizationStatus.provisional) {
print('User granted provisional permission');
} else {
print('User declined or has not accepted permission');
}
}

(If you get "User declined or has not accepted permission" in your console, try going out of your app, finding the icon in the homescreen, pressing and holding on the app icon, tapping "App Info", tapping "Notifications" and turn on "All [app name] notifications."

You will also need two functions to load a Firebase Cloud Messaging notification and one to listen for a notification.

Code to load a Firebase Cloud Messaging notification:

 void loadFCM() async {
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.high,
enableVibration: true,
);

flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);

/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
}

And this function to listen for a Firebase Cloud Messaging notifcation.

void listenFCM() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
// TODO add a proper drawable resource to android, for now using
// one that already exists in example app.
icon: 'launch_background',
),
),
);
}
});
}

You will want to run loadFCM, listenFCM, and requestPermission when the page is initialized.

  void initState() {
super.initState();
requestPermission();
loadFCM();
listenFCM();
}

The next step is to find your Firebase Cloud Messaging API key. This can simply be done by heading to your Firebase project > Project Settings > Cloud Messaging then copy the API key under Cloud Messaging API (Legacy).

When you have your Firebase Cloud Messaging API key, this is the code to display a notification given the notification title, body, and device token to send it to.

  void sendPushMessage(String body, String title, String token) async {
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key=REPLACETHISWITHYOURAPIKEY',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': body,
'title': title,
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
"to": token,
},
),
);
print('done');
} catch (e) {
print("error push notification");
}
}

Now you can call this function like this:

sendPushMessage('Notification Body', 'Notification Title', 'REPLACEWITHDEVICETOKEN');

I hope this helps.

How can I send notification to specific User using the user's token in Firebase?

For sending a notification to users the only thing required is that user's token. You can send notification using FCM.
Here, I'm sharing my FCM class which can be used for this purpose. It is using Okhttp3 requests, so make sure you add its dependency.

    implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'

After adding this dependency, all you have to do is to use this FCM class.

FCMMessages.java

public class FCMMessages {

private Context context;

public void sendMessageSingle(Context context, final String recipient, final String title, final String body, final Map<String, String> dataMap)
{
this.context = context;

Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("body", body);
notificationMap.put("title", title);

Map<String, Object> rootMap = new HashMap<>();
rootMap.put("notification", notificationMap);
rootMap.put("to", recipient);
if (dataMap != null)
rootMap.put("data", dataMap);

new SendFCM().setFcm(rootMap).execute();
}

public void sendMessageMulti(Context context, final JSONArray recipients, final String title, final String body, final Map<String, String> dataMap) {
this.context = context;

Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("body", body);
notificationMap.put("title", title);
Map<String, Object> rootMap = new HashMap<>();
rootMap.put("notification", notificationMap);
rootMap.put("registration_ids", recipients);
if (dataMap != null)
rootMap.put("data", dataMap);

new SendFCM().setFcm(rootMap).execute();
}

@SuppressLint("StaticFieldLeak")
class SendFCM extends AsyncTask<String, String, String> {

private String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
private Map<String, Object> fcm;

SendFCM setFcm(Map<String, Object> fcm) {
this.fcm = fcm;
return this;
}

@Override
protected String doInBackground(String... strings) {
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, new JSONObject(fcm).toString());
Request request = new Request.Builder()
.url(FCM_MESSAGE_URL)
.post(body)
.addHeader("Authorization","key=" + StaticConfig.myMessagingAuth)
.build();
Response response = new OkHttpClient().newCall(request).execute();
return response.body().string();

} catch (Exception e) {
e.printStackTrace();
return null;
}
}

@Override
protected void onPostExecute(String result) {
try {
JSONObject resultJson = new JSONObject(result);
int success, failure;
success = resultJson.getInt("success");
failure = resultJson.getInt("failure");
//Toast.makeText(context, "Sent: " + success + "/" + (success + failure), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Message Failed, Unknown error occurred.", Toast.LENGTH_LONG).show();
}
}
}

}

Make sure you get the messagingAuth from your firebase project settings. To get the messagingAuth token, follow these steps:

Open Firebase Project > Project Settings > Cloud Messaging > Server key

Copy the value of server key and paste it as messagingAuth in your android project.

To send a notification to single user token use sendMessageSingle method. It would be like

String user_token = "wiubd92uhe91dik-q";
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageSingle(MainActivity.this, user_token, notification_title, notification_des, null);

To send a notification to multiple user tokens use sendMessageMulti method. It would be like

ArrayList<String> user_tokens = new ArrayList<>();
user_tokens.add(token_1);
user_tokens.add(token_2);
user_tokens.add(token_3);
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageMulti(MainActivity.this, new JSONArray(user_tokens), notification_title, notification_des, null);

Send notification to one user with firebase cloud function node

Firebase Cloud Messaging has no concept of a user. Instead it can send messages to:

  • Specific app instances (so your specific app as installed on one specific device), as identified by an FCM/device token.
  • A group of app instances/tokens, as defined by your application logic.
  • A specific topic, to which app instances can then subscribe.

It's up to your application logic to decide how to map from your user ID to one of these options. The most common are to:

  • Store the device token(s) and your user ID in your own database, then look up the device token(s) for a user when needed and fill them in to the API call you already have.
  • Use a specific topic for each user ID, subscribe the application to that when it starts, and then send a message to that topic when needed. Note that anyone can subscribe to any topic though, so this approach would allow folks to receive message for anyone whose user ID they know.

How to send FCM messages to a different user

Firebase Cloud Messaging has three ways to target messages:

  1. You send a message to a FCM token/device ID.

    An FCM token identifies a specific app on a specific device, so you're targeting a single app instance.

  2. You send a message to a topic.

    An app instance can subscribe to any topic, so you're targeting everyone who has subscribed to the topic here.

  3. You send a message to a device group.

    You can group FCM tokens into groups of up to 20, which you can then target with a single message.

Of these options, the first and third are by far the most common.

You'll note that there's no options to send a message to a user, as FCM doesn't have the concept of a user. A user can be signed in to the same app on multiple devices, in which case they'd have multiple FCM tokens. And (less common, but still common enough to think about) multiple users can sign into the same app on the same device.

You'll want to set up a database somewhere (sometimes referred to as a token registry) where you map the FCM tokens to how you want to send messages. So in your case, storing the tokens for each user makes sense, and is in fact quite idiomatic.

Can I use fcm to send push notifications to other users?

This is possible with firebase push notifications.
But its not possible to trigger this from client-side. You could accomplish this with a cloud function...



Related Topics



Leave a reply



Submit