2012-11-09 62 views
7

我已阅读过有关GCM的文章,可能会刷新注册ID,无需定期循环。我正在尝试使用推送通知来构建应用程序,但不太确定如何处理此类刷新的注册ID。每次应用程序启动时请求Google Cloud Messaging(GCM)注册ID

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

可以这样做吗?

+0

[处理Android上的Google云消息传递中的注册ID更改]的可能重复(http://stackoverflow.com/questions/16838654/handling-registration-id-changes-in-google-cloud-messaging-on -Android) – Eran

回答

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"); 
    } 
} 

之后,你应该随时应用程序接收到一个com.google.android.c2dm.intent.REGISTRATION意图用registration_id额外的注册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的文档。

希望有帮助!

1

注册刷新不包含在新的GCM库中。的Costin Manolache

的“定期”刷新

词从来没有发生过,而注册刷新不包括在新的GCM库。

注册ID更改的唯一已知原因是应用程序 的旧bug如果在 升级时收到消息而自动取消注册。在此错误修复之前,应用程序在升级后仍需要调用 register(),并且到目前为止,此情况下注册ID可能会更改为 。显式调用unregister()通常也会更改 注册ID。

建议/解决方法是生成您自己的随机标识符 ,例如保存为共享首选项。在每次应用升级时,您可以上传 标识符和潜在的新注册ID。此 也可能有助于跟踪和调试服务器端的升级和注册 更改。

相关问题