Clearing app data not clearing GCM token nor GCM subscribing topics - android

I had subscribed to topics from GCM and when I removed all app data by android settings, the GCM token is the same and GCM notification on topics are still available, so I get notifications which I don't want to receive.
My questions are:
How can I get list all of subscribed topics from GCM?
How can I remove all subscribed topics without knowing their names?
Should the GCM token be changed after clearing app data or should all subscribed topics be removed automatically in this case?

You can't only you can use tool for debug i suggest :)
You have to save subscribed topics for example in sharedprefs. If you don't have token in sharedpreferences you should call instanceId.deleteInstanceID()
Simply call instanceId.deleteInstanceID()
Token will change rarely but when it changes you must resubscribe all your topics.
Also checkout this question on SO
TOOL
You can use this tool to debug :)
When i don't subscribe any topic i get something like this:
{
"applicationVersion": "39",
"connectDate": "2016-01-12",
"application": "com.esportlivescore.develop.debug",
"authorizedEntity": "114434000000000",
"connectionType": "MOBILE",
"appSigner": ".................",
"platform": "ANDROID"
}
After i subscribe some topic:
{
"applicationVersion": "39",
"connectDate": "2016-01-12",
"application": "com.esportlivescore.develop.debug",
"authorizedEntity": "11443413691531",
"rel": {
"topics": {
"match-28388-start": {
"addDate": "2016-01-13"
}
}
},
"connectionType": "MOBILE",
"appSigner": ".................",
"platform": "ANDROID"
}
So somple usage. I use Advanced REST Client (plugin for Chrome)
HTTP GET Request
https://iid.googleapis.com/iid/info/<TOKEN>?details=true
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
TOKEN in url : token obtainet from google
key : can be found in Google Developer Console / GCM Console

How can I get list all of subscribing topics from gcm?
The current version of GCM doesn't provide a method to do this.
How can I remove all of subcribing topics without knowing their names?
The documentation indicates InstanceId.deleteInstanceID() will do this.
Should GCM token be changed after clear app data or removed all
subscribing topics in this case automatically?
Although the documentation implies that token registrations and subscriptions are removed if the user clears app data, that is not true in the current version of GCM. The issue is discussed in the answer to this related question.

Related

Pushing Notification to all users in Firebase

I am trying to send push notifications using python to all users. However, I am aware that there is no way to do this using apps and you have to use topics (as far as I am aware).
Is there a way that I can create a topic out of the app?
Thanks
Edit: I am completely new to firebase (so sorry if I am difficult)
First of all you need to understand a topic does not need to create (it will be create automatically), you only need to define the topic name for example if you are creating app to receive push notification when the weather change, so the topic name could be "weather".
Now you need have 2 components: mobile & backend
1. Mobile: in your mobile app you only need integrate the Firebase SDK and subscribe to the topic "weather" how do you do that?
Firebase.messaging.subscribeToTopic("weather")
Don't forget checking documentation.
2. Backend: in your server you will need to implement the sender script based on FCM SDK.
If you are a beginner I'd recommend you use Postman to send push notifications and then integrate FCM in your backend app.
You can send this payload trough Postman (don't forget set your API KEY in headers)
https://fcm.googleapis.com/fcm/send
{
"to": "/topics/weather",
"notification": {
"title": "The weather changed",
"body": "27 °C"
}
}
If that works, you can add FCM SDK to your backend:
$ sudo pip install firebase-admin
default_app = firebase_admin.initialize_app()
Finally you can send notifications as documentation says:
from firebase_admin import messaging
topic = 'weather'
message = messaging.Message(
notification={
'title': 'The weather changed',
'body': '27 °C',
},
topic=topic,
)
response = messaging.send(message)
More details here: https://github.com/firebase/firebase-admin-python/blob/eefc31b67bc8ad50a734a7bb0a52f56716e0e4d7/snippets/messaging/cloud_messaging.py#L24-L40
You need to be patient with the documentation, I hope I've helped.
The above solutions are depreciated and outdated.
Let me include the latest implementation of firebase-admin SDK for python.
import firebase_admin
from firebase_admin import credentials, messaging
cred = credentials.Certificate(
"<path-to-your-credential-json>")
firebase_admin.initialize_app(cred)
topic = 'notification'
message = messaging.Message(
notification=messaging.Notification(
title='The weather changed', body='27 °C'),
topic=topic,
)
response = messaging.send(message)
print(response)
*Note of few configurations:
Obtain your credential.json in your firebase console under: "Project settings" -> "Service accounts" -> "Generate new private key"
Make sure you subscribe to the correct topic name for both of your server and client application. Every client applications that subscribed to the same topic regardless of which devices will received the corresponding notifications.
Have a good day~
To subscribe an Android client to a topic, do as shown in the documentation on subscribing to a topic:
FirebaseMessaging.getInstance().subscribeToTopic("weather")
Then you can send a message to that topic from a trusted environment, such as your development machine, a server you control, or Cloud Functions. For an example of this, see How do you send a Firebase Notification to all devices via CURL?

Firebase subscribe to a topic dynamically

I have a scenario in my app such that, a certain event occurs and I have a list of user-id/tokens and I need to send the notification to all of those n devices.
To trigger the fcm with n tokens , n time will not be feasible
so I should create a topic dynamically and subscribe those n users's device id/ token to that topic.
I know I can do it from the client app , but is it possible to do that from backend.
I am using Phoenix as my backend.
I found the way, writing this answer in case it help others in future
Yes Its possible to create a topic dynamically if we have the list of
valid registration tokens
This is the endpoint url if you want to generate a topic , given you have a list of users-
https://iid.googleapis.com/iid/v1:batchAdd
The Authorization header contains-
Content-Type- application/json
Authorization- key=<your-server-key>
The body parameters look like-
{
"to": "/topics/<topic name>",
"registration_tokens": [
"token1",
"token2"
]
}
And now the topic is created,
You can easily sen message to that topic with- https://fcm.googleapis.com/fcm/send
Authorization token is same as previous one
And body as-
{
"priority": "HIGH",
"notification": {
"title": "New Text Message",
"image": "https://firebase.google.com/images/social.png",
"body": "Hello how are you?"
},
"to": "/topics/<topic name>"
}
To trigger the fcm with n tokens , n time will not be feasible
Using topics does not inherently change how FCM message delivery works. When you use a topic, the Google servers keep a mapping of that topic to the subscribed tokens. So when you call the API to send a message to a topic, the Google servers fan-out from that topic to the tokens, and then deliver the message with the same infrastructure as when you call the API with the tokens yourself.
Since you already have the tokens, so it might be simpler to just send to them directly, rather than creating a one-off topic.

Real-time Developer Notifications Not Sending IAP Subscription Event Messages

After setting up Android real-time developer notifications (RTDN) as a way to receive IAP subscription state changes to my web server, I only actually receive a certain push from Google's RTDN webhook that never includes the subscription details. Below is the payload structure that gets delivered to my server every time a purchase subscription event happens from my app:
"message": {
"data": "longstringofcharacters",
"messageId": "604411111111111",
"message_Id": "60442222222222",
"publishTime": "2019-07-03T11:03:34.076Z",
"publish_time": "2019-07-03T11:03:34.076Z",
},
"subscription": "projects/api-keyname/subscriptions/my-project-name"
According to Google's RTDN setup guide (https://developer.android.com/google/play/billing/realtime_developer_notifications.html), the below format is what I should expect to receive anytime a new subscription is purchased, cancelled, restored, or undergoes any other related state change from a user in my app:
{
"version": string,
"packageName": string
"eventTimeMillis": long
"subscriptionNotification": SubscriptionNotification
"testNotification": TestNotification
}
I have gone through Google's RTDN setup guide a number of times, and made sure my topic has granted publisher permissions for "Pub/Sub Publisher" using "google-play-developer-notifications#system.gserviceaccount.com" which Google says is a necessary step; doing this I believe is the reason why I'm able to receive webhook transmissions, but for some reason I don't understand why subscriptions events aren't getting transmitted.
Ultimately, my goal is to receive the correct payload which contains IAP state change details so that automatically syncs with my user database on my server.
Has anyone experienced this with RTDN when attempting to receive IAP push notifications?
I figured it out: I missed in Google's guide that the payload I was expecting was base64 encoded in the "data": "longstringofcharacters" portion I pasted above. Once I realized that, I decoded one from my logs, and found the IAP subscription details I was expecting.

How does one distinguish between Android and IOS Firebase IDs for Push Notifications?

As per my previously asked question, Firebase onMessageReceived not called when app is in the background , I need to change the payload to a 'data' payload as opposed to a 'notification' payload. (See link here -- What is the difference between Firebase push-notifications and FCM messages?).
The problem is, both the IOS and Android app we have utilize Firebase and the IOS app requires the push notification payload to use the 'notification' structure, while Android requires the 'data' payload structure.
My question is therefore, how do you distinguish between Android and IOS tokens / Ids obtained via the firebase sdk?
If our server saves these Ids and needs to send out a push notification, it needs to specify Android vs IOS in order to change the payload structure. Is the only way to accomplish this identification to have an app-based call to the server which differentiates IOS vs Android? Or is there a more sophisticated way using Firebase that will allow us to poinpoint which device it is?
Thanks all.
Information about an app instance is available from the Instance ID Service at this endpoint:
https://iid.googleapis.com/iid/info/IID_TOKEN
On success the call returns HTTP status 200 and a JSON object containing various status for the app instance including the platform:
returns ANDROID, IOS, or CHROME to indicate the device platform to
which the token belongs
I faced the same issue, following is my approach to solve the issue.
Firebase supports "Topic messaging", in which we can send data or notification messages to multiple subscribed devices.
Lets consider user login email id is unique (Lets consider example email id is test#gmail.com), In android application user will subscribe to test_gmail.com_data topic (replace '#' with '_' in email id since topic name doesn't support '#') and in iOS application user will subscribe to test_gmail.com_notification topic, From cloud functions I am sending Data message which is intended to android device on data topic and Notification message which is intended to iOS devices on notification topic.
By this approach I solved the issue, only problem with this approach is we end up sending twice the same message.
Example Code :
const data_message = {
data: {
"sender": "Narendra",
"Message" : "Simple data message"
},
topic:"test_gmail.com_data"
};
const notification_message = {
notification: {
title: "Announcement"
},
data: {
"sender": "Narendra",
"Message" : "Simple data message"
},
topic: "test_gmail.com_notification"
};
promises.push(admin.messaging().send(data_message));
promises.push(admin.messaging().send(notification_message));

GCM re-subscribe topics after onTokenRefresh()

From Google Developer website, I found that GCM Token may be changed after period of time:
The Instance ID service initiates callbacks periodically (for example,
every 6 months), requesting that your app refreshes its tokens. It may
also initiate callbacks when:
There are security issues; for example, SSL or platform issues.
Device information is no longer valid; for example, backup and restore.
The Instance ID service is otherwise affected.
I have an android app using GCM Topic subscriptions to send push notification, in this case, when token has been refreshed, do I need to re-subscribe all topics again or GCM server will automatically do it ?
Thank you in advance.
I have tested that when token is refreshed (you receive a new token) you have to register all topics again.
Also checkout this SO
Sample test:
Get token ("...b43sCSdoEDkU54SIWll3hbDVsd7E1UdwlAvp4LP")
Register for topic.
Send notification for topic
Works!
Restart few times app and still get notification for topic
Force call
instanceID.getToken(defaultSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
Token refreshed ("...XVT_pZq7fy_vKmskiGpDXMyqdAF6ODl_46JMdi5")
Send notification for topic. I don't get it!
More details:
Tool #1
Use this to check google gcm data
Reinstall app
Get new token ("")
Response from tool #1
{
"applicationVersion": "39",
"connectDate": "2016-01-12",
"application": "com.esportlivescore.develop.debug",
"authorizedEntity": "11443413691531",
"connectionType": "MOBILE",
"appSigner": ".................",
"platform": "ANDROID"
}
Subscribe for topic
Response from tool #1
{
"applicationVersion": "39",
"connectDate": "2016-01-12",
"application": "com.esportlivescore.develop.debug",
"authorizedEntity": "11443413691531",
"rel": {
"topics": {
"match-28388-start": {
"addDate": "2016-01-13"
}
}
},
"connectionType": "MOBILE",
"appSigner": ".................",
"platform": "ANDROID"
}
Messages for topic are working
Request new token (refresh)
Google resend me old token :)
Again...
Now i don't have any subscriptions :(

Categories

Resources