我在Android上通过本地设备组遵循Google云消息传递(GCM),给出了HTTP错误代码401来管理Android上的本地设备组,并成功获得了通知密钥,但是当我向通知密钥发送消息时,我从未收到消息。有没有人做过这项工作?
我的发送代码是这样的:
public void sendMessage(View view) {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
String to = notificationKey; // the notification key
AtomicInteger msgId = new AtomicInteger();
String id = Integer.toString(msgId.incrementAndGet());
Bundle data = new Bundle();
data.putString("hello", "world");
gcm.send(to, id, data);
Log.e(TAG, "sendMessage done.");
} catch (Exception ex) {
Log.e(TAG, ex.toString());
}
return null;
}
};
task.execute();
}
似乎对GCM概念存在误解。应用服务器是 GCM 消息传递不可或缺的一部分。
Google Cloud Messaging (GCM) 的服务器端由两个组成 组件:
- 谷歌提供的 GCM 连接服务器。这些服务器接收消息 从应用服务器,并将其发送到设备上运行的客户端应用。 Google 提供 HTTP 和 XMPP 的连接服务器。
- 一个应用程序 必须在环境中实现的服务器。此应用程序 服务器通过所选的 GCM 连接将数据发送到客户端应用程序 服务器,使用适当的 XMPP 或 HTTP 协议。
尝试Android GCM Playground以更好地了解这一点。
下面是一个片段:
public void sendMessage() {
String senderId = getString(R.string.gcm_defaultSenderId);
if (!("".equals(senderId))) {
String text = upstreamMessageField.getText().toString();
if (text == "") {
showToast("Please enter a message to send");
return;
}
// Create the bundle for sending the message.
Bundle message = new Bundle();
message.putString(RegistrationConstants.ACTION, RegistrationConstants.UPSTREAM_MESSAGE);
message.putString(RegistrationConstants.EXTRA_KEY_MESSAGE, text);
try {
gcm.send(GcmPlaygroundUtil.getServerUrl(senderId),
String.valueOf(System.currentTimeMillis()), message);
showToast("Message sent successfully");
} catch (IOException e) {
Log.e(TAG, "Message failed", e);
showToast("Upstream FAILED");
}
}
}
send 方法的 to 字段表示项目的发送方 ID。您无法使用此方法将消息发送到实例 ID 令牌(其他设备),GCM 当前不支持设备到设备消息传递。
避免在客户端应用中包含 API 密钥是正确的,因此目前需要应用服务器来发送这些类型的消息。