可以在GoogleCloudMessaging中拥有多个接收者ID吗?

时间:2014-12-19 15:48:51

标签: android google-cloud-messaging

我正在学习本教程:

http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

我的应用程序正在获取gcm_regid,它存储在mysql中。有了这个id,我可以通过php发送消息给选择的regid;

但是当我卸载应用程序 - 并重新安装时,它会得到一个新的reg_id - 也没关系,这也存储在mysql中。

但是当我向第一个gcm_regid发送消息时(这是以前的gcm_regid),手机也正在收到该消息,即使它有一个新的gcm_regid(由于重新安装) - 为什么会这样,我怎么能删除以前的ID? 那个id在哪里?在我的设备?存储在gcm服务器中?

和第二个问题:

当我将上述教程中的GCMRegistrar更改为Google Cloud Messaging时,我是否必须更改主要内容 - 我必须在那里做什么

1 个答案:

答案 0 :(得分:0)

当GCM为您的设备分配新的注册ID时,分配给它的先前ID将继续有效。如果您向分配给设备的较旧注册ID发送消息,则会传递消息,但您的服务器将收到包含规范注册ID的响应,该ID是该设备的最新注册ID。如果您收到此类回复,则应从数据库中删除旧的注册ID。

关于您的第二个问题,您不必进行重大更改,以便停止使用GCMRegigtrar并改为使用GoogleCloudMessaging。实际上,在进行更改后,您的代码应该看起来更简单。

  1. 在您的某项活动中,您将在AsyncTask内有一次对GoogleCloudMessaging.register的调用。必须在AsyncTask中调用此方法,因为它阻塞,因此无法在主线程上执行。关于它的好处是你可以在你调用方法的同一个地方获得响应,而不必在GCMBroadCastReceiver / IntentService中等待它。

  2. 您的GCMBroadcastReceiver / IntentService必须只处理传入的消息。他们不再需要处理注册了。

  3. 以下是新注册流程的部分示例,取自official GCM Demo

    /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration ID and the app versionCode in the application's
     * shared preferences.
     */
    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @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.
                    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 regID - 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);
    }
    
相关问题