I would like to send the GCM deviceToken
to my server so I can initiate push notifications using Parse's REST API. This all works, except that I can't reliably get the deviceToken
when it becomes available. When I register the app to receive push notifications on the broadcast channel, I check for the deviceToken
in the done()
callback. However, it is often not yet set. I'm looking for a way to get the deviceToken
the moment it becomes available, so I can avoid polling or waiting until the app restarts to send push notifications.
Grabbing deviceToken in channel registration callback
Parse.initialize(this, applicationId, clientKey) {
ParsePush.subscribeInBackground("", new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
String deviceToken = (String) ParseInstallation.getCurrentInstallation().get("deviceToken");
// deviceToken is often still null here.
}
}
});
Grabbing deviceToken in ParseInstallation.saveInBackground()
final ParseInstallation parseInstallation = ParseInstallation.getCurrentInstallation();
parseInstallation.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
String deviceToken = (String) parseInstallation.get("deviceToken");
// deviceToken is often still null here.
}
});
Listening for the GCM registration event myself by subclassing com.parse.GcmBroadcastReceiver
// Which I can't do, because it's declared final.
public final void onReceive(Context context, Intent intent) {
PushService.runGcmIntentInService(context, intent);
}
The purpose of the deviceToken
field is to store the subscription id required to deliver messages to this device via GCM. Intercepting the GCM registration calls to grab the registration id for the sole purpose of targeting push notifications to this device may not be the best approach.
While you could use the deviceToken
in a query to target push notifications to this device, you may want to consider using any of the other fields on the installation object itself. Keep in mind that a ParseInstallation
object extends ParseObject
, so you are able to add any fields to the installation object that can help you target push notifications to this device.
If you don't have any specific criteria that helps you unique identify this one user of your app and you're looking for a unique identifier, may I suggest saving the objectId
on your server for targeting purposes? The objectId
is available as soon as the installation save callback is executed, regardless of the current state of the GCM registration process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With