我今天学习了 GCM 服务器。阅读 developer.android.com 部分 GCM 中的内容,我仍然不确定如何在第三方服务器中管理注册 ID。我的理解是:
- android 应用程序可以在 GCM 服务器上注册和注销其 ID。
- 服务器端可以使用注册ID和
向设备发送消息 服务器 key 。
那么,如何从 GCM 服务器获取设备注册 ID?我需要直接从 Android 设备获取吗?
感谢您的建议。
最佳答案
了解基本信息最好的地方是here在 developer.android.com
您将在他们的教程中看到此示例代码:
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.
// Persist the registration ID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
...
}
如果我理解正确,您对如何将 GCM RegistrationId 获取到您的服务器实现感到困惑。您可以在您将定义的 sendRegistrationIdToBackend()
方法中执行此操作。
您需要创建一个端点来接收 POST 请求,每台设备在收到来自 GCM 的请求后都会将其 RegistrationID 发布到该请求。然后您的服务器实现将知道所有安装了您的应用程序并已向 GCM 注册的设备。
注意:您可能需要注意的一件事是,如果设备最终两次发布其 RegistrationID,或者用户卸载然后重新安装应用程序但 GCM 为他们提供了相同的 RegistrationID,您最终可能会得到相同的 RegistrationID副本存储在服务器上的数据库中。如果发生这种情况并且您想向所有用户发送推送,那么您的一些用户可能最终会收到多个推送通知,具体取决于数据库中有多少重复项。
关于android - 在服务器中管理 GCM 注册 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977779/