我正在使用FCM发送通知android设备,有时它们的通知正通过设备发送,有时我会收到错误:错误的设备令牌,无效的设备令牌
在node.js中发送通知代码:
var gcm = require('node-gcm');
var apiKey = '';
exports.push_notification = push_notification;
function push_notification(data){
var message = new gcm.Message({
collapseKey: 'demo',
priority: 'normal',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 3,
data:data
});
var sender = new gcm.Sender(apiKey);
var regTokens = [data.notification_id];
sender.send(message, { registrationTokens: regTokens}, function (err, response) {
if (err){
console.log("++++++++++++++++++++++++++++++++",err);
} else {
//console.log(regTokens);
//console.log(response);
}
});
}
在Android端处理消息并接收令牌代码:
@Override
public void onNewToken(String token) {
super.onNewToken(token);
storeRegIdInPref(token);
sendRegistrationToServer(token);
Intent registrationComplete = new Intent(GlobalConstants.REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", token);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
try { handleDataMessage(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), "", "", remoteMessage.getNotification().getTag());
} catch (Exception e) {
e.printStackTrace();
}
}
if (remoteMessage.getData().size() > 0) {
String title="", message="", imageUrl="", timestamp="",type="other";
try {
title = remoteMessage.getData().get("title");
message = remoteMessage.getData().get("message");
type = remoteMessage.getData().get("type");
if (((new ValidationsClass()).checkStringNull(type)))
type = "other";
imageUrl = remoteMessage.getData().get("image");
timestamp = remoteMessage.getData().get("timestamp");
} catch (Exception e) {
}
handleDataMessage(title, message, imageUrl, timestamp, type);
}
}