使用Pub/Sub模型在Ionic 2中推送通知
问题描述:
我正在使用phonegap-plugin-push插件在Ionic 2 Chat App中执行推送通知。使用Pub/Sub模型在Ionic 2中推送通知
我已经根据documentation实现了它,它工作,但只在同一个设备上。即,如果您提供device token
,它会向手机发送通知。
我的问题是针对一个聊天应用程序,我需要一个PubSub模型。因此,用户可以发布到某个主题,而另一个用户可以订阅该主题,即使他们处于不同的解决方案。
看着documentation,它似乎是可能的。见android.topics
和ios.topics
。
android.topics array []可选。如果数组包含一个或多个 字符串,则每个字符串将用于订阅GcmPubSub主题。
所以我尝试以下方法:
JavaScript客户端:
发布
let push = Push.init({
android: {
senderID: "xxxxxxxx",
topics: ['foo']
},
ios: {
alert: "true",
badge: false,
sound: "true",
topics: ['foo']
},
windows: {}
});
push.on('registration', (data) => {
// call the Java Server
let promise: Promise<string> = this.notificationService.push(data.registrationId, 'This is a test message from Ionic Chat');
promise.then((data) => {
});
});
Java服务器:
try {
System.out.println("NotificationService: device_token: "+device_token);
logger.info("NotificationService: device_token: "+device_token);
// Prepare JSON containing the GCM message content. What to send and where to send.
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put("title", "This is title");
jData.put("message", message);
jGcmData.put("to", device_token); // <===== is this the problem???? it is the data.registrationId from the client
// What to send in GCM message.
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://gcm-http.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + API_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
} catch (Exception e) {
e.printStackTrace();
}
JavaScript客户端:
订阅
let push = Push.init({
android: {
senderID: "xxxxxxxx",
topics: ['foo']
},
ios: {
alert: "true",
badge: false,
sound: "true",
topics: ['foo']
},
windows: {}
});
push.on('notification', (data) => {
});
它可以在同一设备上,但如果publisher
和subscriber
在不同的设备不工作。
我认为问题可能是即使另一个用户订阅了我发布的主题,它仍然只发布到data.registrationId
(设备令牌)。
,请参阅Java服务器上以下行:
jGcmData.put("to", device_token);
问题
有谁知道如何使它发送到有关该主题的所有订阅者?
我想答案是here:
"to": "/topics/foo-bar",
但是如何把这个多个主题进行格式化?(这只是一个话题foo-bar
)
答
需要改变Java服务器发送到话题的设备,而不是:
jGcmData.put("to", "/topics/"+topics);