推送的原理其實也很簡單,拿極光推送來說,首先,APP登錄的時候,調用極光的API,設置當前登錄的信息到極光;服務器發送推送時,只要將需要推送的信息和相應的唯一標識傳給極光,就可以了。
附上服務器端簡單代碼:
public static void testSendPush(String appKey ,String masterSecret,
String jsonString,String alias) {
try {
MSG_CONTENT = jsonString;
jpushClient = new JPushClient(masterSecret, appKey, 3);
PushPayload payload = buildPushObject_android_and_ios(jsonString, alias);
PushResult result = jpushClient.sendPush(payload);
LOG.info("Got result - " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
LOG.info("Msg ID: " + e.getMsgId());
}
}
public static PushPayload buildPushObject_android_and_ios(String jsonString,String alias) {
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.newBuilder()
.addAudienceTarget(AudienceTarget.alias(alias))
.build())
.setMessage(Message.newBuilder()
.setMsgContent(jsonString)
.addExtra("from", "JPush")
.build())
.build();
}