每次应用程序启动时请求Google Cloud Messaging(GCM)注册ID

chi*_*ker 7 android push-notification google-cloud-messaging

我读过有关GCM的文章可能会刷新注册ID而没有常规周期.我正在尝试使用推送通知构建应用程序但不太确定如何处理这样刷新的注册ID.

我的第一个策略是每次应用启动时请求注册ID并将其发送到应用服务器.它看起来有效,但听起来有点不对劲......

可以这样做吗?

Nic*_*las 5

基本上,您应该在主要活动中执行以下操作:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout);

    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);

    final String regId = GCMRegistrar.getRegistrationId(this);

    if (regId.equals("")) {
        GCMRegistrar.register(this, GCMIntentService.GCM_SENDER_ID);
    } else {
        Log.v(TAG, "Already registered");
    }
}
Run Code Online (Sandbox Code Playgroud)

之后,只要应用程序收到额外的com.google.android.c2dm.intent.REGISTRATION意图,您就应该将注册ID发送到您的应用服务器registration_id.当Google定期更新应用的ID时,可能会发生这种情况.

您可以通过扩展com.google.android.gcm.GCMBaseIntentService自己的实现来实现这一目标,例如:

public class GCMIntentService extends GCMBaseIntentService {

    // Also known as the "project id".
    public static final String GCM_SENDER_ID = "XXXXXXXXXXXXX";

    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(GCM_SENDER_ID);
    }

    @Override
    protected void onRegistered(Context context, String regId) {
        // Send the regId to your server.
    }

    @Override
    protected void onUnregistered(Context context, String regId) {
        // Unregister the regId at your server.
    }

    @Override
    protected void onMessage(Context context, Intent msg) {
        // Handle the message.
    }

    @Override
    protected void onError(Context context, String errorId) {
        // Handle the error.
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,我将(重新)阅读用于编写客户端代码GCM文档高级部分的文档.

希望有所帮助!