Receive messages from 2 different senders in FCM [duplicate] - android

I want to be able to add more than one sender id in my android app.
From https://developers.google.com/cloud-messaging/concept-options
GCM allows multiple parties to send messages to the same client app. For example, suppose the client app is an articles aggregator with multiple contributors, and each of them should be able to send a message when they publish a new article. This message might contain a URL so that the client app can download the article. Instead of having to centralize all sending activity in one location, GCM gives you the ability to let each of these contributors send its own messages.
How is this achieved using google-services.json configuration file?

UPDATE: Going to refer to the official and recommended way in doing this instead of the hacky and unofficial approach to prevent/avoid unknown problems. From my answer here.
There is actually a part in the documentation about this topic:
Receiving messages from multiple senders
FCM allows multiple parties to send messages to the same client app. For example, suppose the client app is an article aggregator with multiple contributors, and each of them should be able to send a message when they publish a new article. This message might contain a URL so that the client app can download the article. Instead of having to centralize all sending activity in one location, FCM gives you the ability to let each of these contributors send its own messages.
To make this possible, make sure each sender generates its own sender ID. See the client documentation for your platform for information on on how to obtain the FCM sender ID. When requesting registration, the client app fetches the token multiple times, each time with a different sender ID in audience field.
Finally, share the registration token with the corresponding app servers (to complete the FCM registration client/server handshake), and they'll be able to send messages to the client app using their own authentication keys.
Note that there is limit of 100 multiple senders.
I think the confusing but important part here is:
When requesting registration, the client app fetches the token multiple times, each time with a different sender ID in audience field.
In other terms, you'll have to call getToken() passing the Sender ID and simply "FCM" (e.g. getToken("2xxxxx3344", "FCM")) as the parameters. You'll have to make sure that you call this for each sender (project) that you need.
Also, note from the getToken() docs:
This is a blocking function so do not call it on the main thread.
Some additional good-to-knows:
It does not auto retry if it fails like the default one.
It returns an IOException when it fails.

As of Dec. 2016, there's a very simple, non-hacky way to do this, which still works now (Jul 2018).
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:something:android:something_else") // Required for Analytics.
.setApiKey("your apikey") // Required for Auth.
.setDatabaseUrl("https://your-database.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "secondary");
Source: The official Firebase blog

Comma seperated senderID solution is still working and able to register same token for 2 different sender. I sent push notif to that single magical token with using 2 different api key and able to receive push notifs for both api key. Hope it works at least till the end of 2020. Because I'm trying to make a seamless transition between an old GCM and FCM projects which targets more than 1 million user. (hear me google and thank you google for not deprecating this great solution)
String magicalToken = FirebaseInstanceId.getInstance().getToken("senderId, anotherSenderId", "FCM");

You can get the single token for multiple sender by passing them as comma separated string and then these sender will be able to send the push notification using the common token, try calling
FirebaseInstanceId.getInstance() .getToken("senderId1,senderId2",
FirebaseMessaging.INSTANCE_ID_SCOPE);
make sure you call this from a background thread.

Related

How to change Firebase topic for some users in specified time?

We have an Android education app and we use FCM Topic Messaging for sending specific notifications to each user. We categorized each user according to academic year.
Now, we have one problem for topic messaging, in the specified time, these students goes to one level higher and if we don't change the topic in Firebase for new academic year, it gives the last year notification.
How can we do this? Does Firebase have a solution for this problem? Thanks <3
This can be done through your App Server by using the InstanceID API.
You can batchAdd the corresponding tokens to the new topic (i.e. academicy year) you need, then batchRemove them from the old topic (i.e. last year).
From the link above:
Manage relationship maps for multiple app instances
Using the Instance ID service's batch methods, you can perform batch management of app instances. For example, you can perform bulk addition or removal of app instances to an FCM or GCM topic. To manage app instances, call the Instance ID service at this endpoint, providing the app instance tokens in the JSON body:
https://iid.googleapis.com/iid/v1:batchAdd
https://iid.googleapis.com/iid/v1:batchRemove
Parameters
Authorization: key=YOUR_API_KEY. Set this parameter in the header.
to : The topic name.
registration_tokens : The array of IID tokens for the app instances you want to add or remove.
Results
On success the call returns HTTP status 200. Empty results indicate successful subscription for the token. For failed subscriptions, the result contains one of these error codes:
NOT_FOUND — The registration token has been deleted or the app has been uninstalled.
INVALID_ARGUMENT — The registration token provided is not valid for the Sender ID.
INTERNAL — The backend server failed for unknown reasons. Retry the request.
TOO_MANY_TOPICS — Excessive number of topics per app instance.
Example POST request
https://iid.googleapis.com/iid/v1:batchAdd
Content-Type:application/json
Authorization:key=API_KEY
{
"to": "/topics/movies",
"registration_tokens": ["nKctODamlM4:CKrh_PC8kIb7O...", "1uoasi24:9jsjwuw...", "798aywu:cba420..."],
}
Example result
HTTP 200 OK
{
"results":[
{},
{"error":"NOT_FOUND"},
{},
]
}

Is a GCM Registration Token equal to the GCM Registration ID ?

i got confused by gcm today. I dont know if my registrationid is correct. I got characters and a colon in front of a registrationid starting with APA. The Pattern is xXXXxxX:APA... . I implemented google cloud messaging for a android client using the example from here: https://developers.google.com/cloud-messaging/android/client . If i use a older implementation (for example with GCMRegistrar) i only get a registration id starting with APA. Till now i though a registration id has to start with APA.
Is the stuff before the colon some tokenspecific stuff? Do i have to pass the full token to the webservice or is it okay if i cut the chars before the colon and send the registration starting with APA?
GCM Registration Token is equal to registration_id. As I mentioned in my answer here:
An FCM Token, or much commonly known as a registrationToken like in google-cloud-messaging. As described in the GCM docs:
An ID issued by the GCM connection servers to the client app that allows it to receive messages. Note that registration tokens must be kept secret.
Different terms point to the same thing. The format for the registration token may also vary as seen this answer:
The GCM registration token is usually around 140 chars in length, and can contain colons, underscores and hyphens. Maximum size is supposed to be 4k.
Though I'm not entirely sure with regards to the character length, I think I've read on a post here somewhere that it may exceed that number. Do search around.
gcm.register() is deprecated. use instance id method with token instead.
https://developers.google.com/cloud-messaging/android/legacy-regid
GCM register() is deprecated starting May 28, 2015. New app
development should use the Instance ID API to handle the creation,
rotation, and updating of registration tokens. For more information,
see Registering Client Apps and Set up a GCM Client App on Android.

How to put multiple project_number/sender id in google-services.json

I want to be able to add more than one sender id in my android app.
From https://developers.google.com/cloud-messaging/concept-options
GCM allows multiple parties to send messages to the same client app. For example, suppose the client app is an articles aggregator with multiple contributors, and each of them should be able to send a message when they publish a new article. This message might contain a URL so that the client app can download the article. Instead of having to centralize all sending activity in one location, GCM gives you the ability to let each of these contributors send its own messages.
How is this achieved using google-services.json configuration file?
UPDATE: Going to refer to the official and recommended way in doing this instead of the hacky and unofficial approach to prevent/avoid unknown problems. From my answer here.
There is actually a part in the documentation about this topic:
Receiving messages from multiple senders
FCM allows multiple parties to send messages to the same client app. For example, suppose the client app is an article aggregator with multiple contributors, and each of them should be able to send a message when they publish a new article. This message might contain a URL so that the client app can download the article. Instead of having to centralize all sending activity in one location, FCM gives you the ability to let each of these contributors send its own messages.
To make this possible, make sure each sender generates its own sender ID. See the client documentation for your platform for information on on how to obtain the FCM sender ID. When requesting registration, the client app fetches the token multiple times, each time with a different sender ID in audience field.
Finally, share the registration token with the corresponding app servers (to complete the FCM registration client/server handshake), and they'll be able to send messages to the client app using their own authentication keys.
Note that there is limit of 100 multiple senders.
I think the confusing but important part here is:
When requesting registration, the client app fetches the token multiple times, each time with a different sender ID in audience field.
In other terms, you'll have to call getToken() passing the Sender ID and simply "FCM" (e.g. getToken("2xxxxx3344", "FCM")) as the parameters. You'll have to make sure that you call this for each sender (project) that you need.
Also, note from the getToken() docs:
This is a blocking function so do not call it on the main thread.
Some additional good-to-knows:
It does not auto retry if it fails like the default one.
It returns an IOException when it fails.
As of Dec. 2016, there's a very simple, non-hacky way to do this, which still works now (Jul 2018).
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:something:android:something_else") // Required for Analytics.
.setApiKey("your apikey") // Required for Auth.
.setDatabaseUrl("https://your-database.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "secondary");
Source: The official Firebase blog
Comma seperated senderID solution is still working and able to register same token for 2 different sender. I sent push notif to that single magical token with using 2 different api key and able to receive push notifs for both api key. Hope it works at least till the end of 2020. Because I'm trying to make a seamless transition between an old GCM and FCM projects which targets more than 1 million user. (hear me google and thank you google for not deprecating this great solution)
String magicalToken = FirebaseInstanceId.getInstance().getToken("senderId, anotherSenderId", "FCM");
You can get the single token for multiple sender by passing them as comma separated string and then these sender will be able to send the push notification using the common token, try calling
FirebaseInstanceId.getInstance() .getToken("senderId1,senderId2",
FirebaseMessaging.INSTANCE_ID_SCOPE);
make sure you call this from a background thread.

How to use GCM Registration ID to send notifications

My team has been developing an app using GCM for the last 4 months, and today we discovered that with the recent update of Google Play Services GCM changed significantly. Until now we've been sending notifications from our backend server to our users using this format of Registration ID:
APA91bF7h6vQkqIaF9ECQ_V............w
That was generated with the classic GoogleCloudMessaging.getInstance(context).register(SENDER_ID) method.
But now, with the new update, you generate the registration ID doing InstanceID.getInstance(this)getToken(SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
and by doing so the generated Registration IDs have the next format:
c3wlROAji5d:APA91bF_iz3Muub6Mu...a6n-ClpQ
Notice how there is first a section of 11 characters followed by a colon and then a long sequence starting with APA91b
So my question is, when sending notifications from my server to my clients should I use the new format as it is or strip the fragment before the colon and use the segment starting with APA91b as before.
Thanks for the attention
You should always use the full registration id to send messages to your users: it is best to think of the registration id as a totally opaque string (i.e., internal structure does not necessarily mean anything).

Registration confusion Android GCM

I am trying to migrate to GCM in Android, C2DM now being deprecated. The registration process described here is different from registration described here. Are both registration same? Can we see code for GCMRegistrar to know for sure?
I've successfully migrated my C2DM project to GCM. Tested, it works fine. The only changes were:
in the Android app - change the value of sender upon registration
on the server side - change the auth header and the URL
That was it, as far as the interaction with Google goes. There were more some changes dictated by the app's logic:
in the Android app, the registration ID was cached in its preferences. Upon upgrade, I remove reg ID from the preferences to force re-registration, this time with GCM.
the logic of passing the reg ID to the server got an extra boolean parameter - if this is a C2DM or GCM reg ID
the logic of sending messages became conditional upon the said parameter.
Throwing out the C2DM logic completely out of the server would be unwise - not everyone upgrades their Android apps. The old, C2DM-enabled versions will be out in the wild for some time. And Google pledged to keep C2DM running in the short term. So message sending is conditional - depending on reg ID type, it sends either to GCM or to C2DM.
EDIT re: conditional logic:
if($RegID_Is_GCM)
{
$Auth = GCM_Auth();
$URL = $GCM_URL;
}
else
{
$Auth = C2DM_AUTH();
$URL = $C2DM_URL;
}
They are actually the same thing. The second one encapsulates the first one in a static method and registers a broadcast receiver. You can attach the source to the gcm.jar and see for yourself. You can find source code in ~/android-sdks/extras/google/gcm/gcm-client/gcm-src.jar
The Thing I like most in GCM is the RegID we will get from GCM server,it is not only an ID its an Address of this application on this Device. So this time you don't need to send a device Id to server along with your Registration Id as per was in C2DM.
In C2DM every time you request a registration id you will get a new ID.
But in GCM RegId generated by using your application package along with some device id so if you will request for Registration Id again and again you will receive the same RegId.
And if you uninstall an application and will install it again still GCM server will give you the same Registration Id.
So one Registraion Id will do no need of any Device Id to send to server.
I have been successful at migrating from C2DM to GCM. I have also documented how to implement GCM at
http://android.amolgupta.in/2012/07/google-cloud-messaging-gcm-tutorial.html
GCMRegistrar is just a helper that does the leg work described in the first page.
You can see the class here. android-sdk\extras\google\gcm\gcmclient\src\com\google\android\gcm.

Categories

Resources