OneSignal offer Push Notification as a service, an Android SDK and a Public API.
Is possible that your flow looks like:
- Get push notification token from device
- Send token to your backend
- Backend uses token and OneSignal API to send pushes.
- Device get the push notification
Ok, Show me code!
We will use the next dependencies:
compile 'com.onesignal:OneSignal:3.0.0@aar'
compile "com.google.android.gms:play-services-gcm:9.2.1"
compile "com.google.android.gms:play-services-analytics:9.2.1"
compile "com.google.android.gms:play-services-location:9.2.1"
Lets use OneSignal Android SDK method to get push ids:
OneSignal.idsAvailable((userId, registrationId) -> {
// Use any of those ids to send the push from backend/server/something
});
userId
: playerId from OneSignalregistrationId
: Google push token
When you check OneSignal API you will see that you can use any of those to create pushes with include_android_reg_ids
and include_player_ids
,
But which one should you use?
Try 1 - Using registrationId
From your server you should do a POST
to https://onesignal.com/api/v1/notifications with:
{
"app_id": "...",
"contents": { "en": "Custom Content" },
"headings": { "en": "Custom Heading" },
"data": { },
"include_android_reg_ids": [ "registrationIdValue"]
}
But you will notice that after some attemps you will get this error:
{
"id": "",
"recipients": 0,
"errors": { "invalid_android_reg_ids": [ "registrationIdValue" ] }
}
Looks like they are having issues since OneSignal.idsAvailable
always returns the same but it becomes invalid based on OneSignal API responses.
Try 2 - using userId (Best Solution)
They said by chat:
We recommend storing userId and using include_player_ids instead. Our system attempts to keep our OneSignal player / user id the same even if the user fully uninstalls and reinstalls your app.
And from docs you will see include_player_ids
param:
include_player_ids: array of stringsOptional. Targeting parameter. An array of OneSignal user IDs (also known as player IDs)
From your server you should do a POST
to https://onesignal.com/api/v1/notifications with:
{
"app_id": "...",
"contents": { "en": "Custom Content" },
"headings": { "en": "Custom Heading" },
"data": { },
"include_player_ids": [ "userIdValue"]
}
Thanks to
Barista Ventures and Sebastian Arcila for the support and help