Lifecycle Flow
Here are the primary processes involved in cloud-to-device messaging:
- Enabling GCM. An Android application running on a mobile device registers to receive messages.
- Sending a message. A 3rd-party application server sends messages to the device.
- Receiving a message. An Android application receives a message from a GCM server.
These processes are described in more detail below.
Enabling GCM
This is the sequence of events that occurs when an Android application running on a mobile device registers to receive messages:
- The first time the Android application needs to use the messaging service, it fires off a registration Intent to a GCM server.
This registration Intent (com.google.android.c2dm.intent.REGISTER
) includes the sender ID(註冊後網址列上的ProjectID), and the Android application ID.(APP名稱)
Note: Because there is no lifecycle method that is called when the application is run for the first time, the registration intent should be sent on onCreate()
, but only if the application is not registered yet.
- If the registration is successful, the GCM server broadcasts a
com.google.android.c2dm.intent.REGISTRATION
intent which gives the Android application a registration ID.
The Android application should store this ID for later use (for instance, to check on onCreate()
if it is already registered). Note that Google may periodically(定期) refresh the registration ID, so you should design your Android application with the understanding that the com.google.android.c2dm.intent.REGISTRATION
intent may be called multiple times. Your Android application needs to be able to respond accordingly.
- To complete the registration, the Android application sends the registration ID to the application server. The application server typically通常 stores the registration ID in a database.
The registration ID lasts持續 until the Android application explicitly明確地
unregisters itself, or until Google refreshes the registration ID for your Android application.
Note: When users uninstall an application, it is not automatically unregistered on GCM. It is only unregistered when the GCM server tries to send a message to the device and the device answers that the application is uninstalled. At that point, you server should mark the device as unregistered (the server will receive a NotRegistered
error).
Note that it might take a few minutes for the registration ID to be completed removed from the GCM server. So if the 3rd party server sends a message during this time, it will get a valid message ID, even though the message will not be delivered to the device.