4

I Have created push notification service using Firebase and I can send notification to either all or single user having FCM id, but I have no idea how to send to specific user.

Also server panel is not created for handling push notification handling If any suggestion for that is there will help more.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Anukool srivastav
  • 807
  • 1
  • 12
  • 20
  • You need customize your web application server selected type like user (admin/provider/customer) via json from your web db – Rajesh Sep 08 '16 at 13:01
  • Firebase Cloud Messaging allows you to target a specific app on a specific device (through a token), a group of devices, all subscribers to a topic, or all users of a specific app. None of these options identifies a single user. One way to target users is to map each user to a topic. This approach is taken in my article on [Sending notification between android devices with Firebase Database and Cloud Messaging](https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html). – Frank van Puffelen Sep 08 '16 at 14:01
  • Thanks @FrankvanPuffelen.. Will follow your article. – Anukool srivastav Sep 11 '16 at 10:43
  • Read this blogpsot for more details. https://medium.com/p/how-to-send-firebase-push-notifications-from-server-tutorial-3f3e3a78f9a5 – Developine Jun 30 '17 at 07:51

4 Answers4

5

Firebase Cloud Messaging (FCM) topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions for each app i.e your group is attached to specific topic like news group,sports group etc.

FirebaseMessaging.getInstance().subscribeToTopic("news");

To unsubscribe unsubscribeFromTopic("news")

From Server side you need to set up for specif topic i.e a group of user like this:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "/topics/news",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

"/topics/news" This will send notification to group of people who have subsribe the news topic

Burhanuddin Rashid
  • 5,260
  • 6
  • 34
  • 51
  • as i can see topics get about 12 hours to be created is there any alternative that is faster ? like groups or something. and can a user be subscribed to more than 1 topic? – George Sep 06 '17 at 12:01
  • 1
    It takes 12 hours to create the topic in Firebase notification console otherwise the topic is created instantly and you can send notification using http request instantly.And Yes user can subscribe to multiple topi – Burhanuddin Rashid Sep 06 '17 at 13:18
  • For group creation you can go for [Device Group Messaging](https://firebase.google.com/docs/cloud-messaging/android/device-group) But its limited to up-to 20 members only in free version – Burhanuddin Rashid Sep 06 '17 at 13:20
  • thanks man you helped a lot i will be using topics, just tested it and it works like a charm :) – George Sep 06 '17 at 15:25
1

In your android code:

    public static void sendNotificationToUser(String user, final String message) {
            Firebase ref = new Firebase(FIREBASE_URL);
            final Firebase notifications = ref.child("notificationRequests");

            Map notification = new HashMap<>();
            notification.put("us

ername", user);
        notification.put("message", message);

        notifications.push().setValue(notification);
    }

Create a node and put this code inside:

    var firebase = require('firebase');
var request = require('request');

var API_KEY = "..."; // Your Firebase Cloud Server API key

firebase.initializeApp({
  serviceAccount: ".json",
  databaseURL: "https://.firebaseio.com/"
});
ref = firebase.database().ref();

function listenForNotificationRequests() {
  var requests = ref.child('notificationRequests');
  ref.on('child_added', function(requestSnapshot) {
    var request = requestSnapshot.val();
    sendNotificationToUser(
      request.username, 
      request.message,
      function() {
        request.ref().remove();
      }
    );
  }, function(error) {
    console.error(error);
  });
};

function sendNotificationToUser(username, message, onSuccess) {
  request({
    url: 'https://fcm.googleapis.com/fcm/send',
    method: 'POST',
    headers: {
      'Content-Type' :' application/json',
      'Authorization': 'key='+API_KEY
    },
    body: JSON.stringify({
      notification: {
        title: message
      },
      to : '/topics/user_'+username
    })
  }, function(error, response, body) {
    if (error) { console.error(error); }
    else if (response.statusCode >= 400) { 
      console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage); 
    }
    else {
      onSuccess();
    }
  });
}

// start listening
listenForNotificationRequests();

More information with the following link, it is the same thing with a many devices:

Sending notification between android devices with Firebase Database and Cloud Messaging

Carlo
  • 813
  • 1
  • 15
  • 34
1

I don't have enough reputation to edit Burhanuddin Rashid's answer but I think what the OP needs is:

You can replace "to: /topics/news" with registration_ids

{ 

   "registration_ids" : [
   "UserInstanceToken1",
   "UserInstanceToken2"
    ]
   "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
    }
}

The User Instance Token can be gotten by

FirebaseInstanceId.getInstance().getToken() in Android.

Okikioluwa
  • 113
  • 9
  • Read this blogpost for more details - > http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ – Developine Nov 11 '17 at 15:39
  • sending notifications to registration id can be done to limited users, @Burhanuddin's answer is the correct approach to this question if you can add some knowledge to that answer – Raj Apr 14 '19 at 19:39
0

Enjoy !

public class NotificationSenderThread implements Runnable {
private String title;
private String message;
private String senderToken;
private String recieverToken;

public NotificationSenderThread(String title, String message, String senderToken, String recieverToken) {
    this.title = title;
    this.message = message;
    this.senderToken = senderToken;
    this.recieverToken = recieverToken;
}

@Override
public void run() {
    try{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", title);
        jsonObject.put("message", message);
        jsonObject.put("fcm_token", senderToken);

        JSONObject mainObject = new JSONObject();
        mainObject.put("to", recieverToken);
        mainObject.put("data", jsonObject);

        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "key=<SERVER KEY>");
        connection.setDoOutput(true);

        Log.e("sent",mainObject.toString());
        DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
        dStream.writeBytes(mainObject.toString());
        dStream.flush();
        dStream.close();

        String line;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder responseOutput = new StringBuilder();
        while((line = bufferedReader.readLine()) != null ){
            responseOutput.append(line);
        }
        bufferedReader.close();
        Log.e("output", responseOutput.toString());
    }
    catch (Exception e){
       Log.e("output", e.toString());
        e.printStackTrace();
    }
}

}