【发布时间】:2013-05-25 11:24:29
【问题描述】:
我在大学最后一年的项目中使用 Google 云消息传递。一切正常,但我在使用 GCM 时遇到了一些麻烦。通常,消息要么几乎立即发送,要么延迟很大。
我已经阅读了这篇文章,但我真的认为它不适用于这种情况:
GCM 通常会在消息发送后立即发送消息。 但是,这可能并不总是可能的。例如,设备 可以关闭、离线或以其他方式不可用。其他 在这种情况下,发件人本身可能会要求不发送消息 直到设备通过使用 delay_while_idle 标志变为活动状态。 最后,GCM 可能会故意延迟消息以防止 应用程序从消耗过多的资源和负面 影响电池寿命。
在我的项目中,每分钟最多谈论来自服务器的 5 或 6 条消息。如果 GCM 可以用于聊天应用程序,他们肯定不能阻止以这种速率发送/接收的消息吗?如果我的项目只在 50% 的时间内有效,它会变得非常烦人并且会非常糟糕......
这是我的服务器发送消息的代码:
@Override
public void run() {
Message.Builder messageBuilder = new Message.Builder().delayWhileIdle(false);
Gson gson = new Gson();
messageBuilder.addData("profile", gson.toJson(profile));
databaseConnection.notifyDevices(messageBuilder.build());
}
public void notifyDevices(Message message) {
Sender sender = new Sender(xxx);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("message", message.toString()));
//LOG
System.out.println("Notifying devices with the following message \n \"" +message+ "\"");
List<String> deviceIDsList = new ArrayList<String>();
String [] deviceIDArray;
//Get devices to notify
List<JSONDeviceProfile> deviceList = getDevicesToNotify();
for(JSONDeviceProfile device : deviceList) {
deviceIDsList.add(device.getDeviceId());
try {
sender.send(message, device.getDeviceId(), 5);
} catch (IOException e) {
System.out.println("Error sending GCM message!");
e.printStackTrace();
}
}
}
还有我的 Android onMessage 方法:
@Override
protected void onMessage(Context arg0, Intent intent) {
String message = intent.getStringExtra("profile");
Log.d(TAG + "Received Message: ", "Received Message: " + message.toString());
//CALL NEW INTENT WITH PROFILE DETAILS
Intent displayProfileIntent = new Intent(arg0, DisplayProfile.class);
displayProfileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
displayProfileIntent.putExtra("message", message);
startActivity(displayProfileIntent);
/*
//generateNotification(arg0, username);
handler.post(new Runnable() {
@Override
public void run() {
//Toast.makeText(getApplicationContext(), username, Toast.LENGTH_SHORT).show();
}
});
*/
}
我希望有人遇到过类似的问题,我只是想确认问题是我正在做的事情,还是我无法控制。
tl;dr GCM 消息要么立即到达,要么大约 10 分钟后到达(延迟通常是一致的)。
【问题讨论】:
标签: java android google-cloud-messaging