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

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

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

可以这样做吗?

解决方法

基本上,您应该在主要活动中执行以下操作:
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");
    }
}

之后,只要应用收到带有registration_id extra的com.google.android.c2dm.intent.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.
    }
}

有关详细信息,我会(重新)阅读writing the client side codethe Advanced Section of the GCM documentation的文档.

希望有所帮助!

相关文章

AdvserView.java package com.earen.viewflipper; import an...
ImageView的scaleType的属性有好几种,分别是matrix(默认)...
文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win1...
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由main...
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件...
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项...