GCM Message Push

Source: Internet
Author: User

1 GCM Introduction

GCM (Google Cloud Message for Android) is an Android server push (push) technology released by Google. The previous C2DM (Android Cloud to Device Messaging) has been formally deprecated with June 26, 2012, using GCM to apply for Google Apis,google APIs including all Google services APIs. such as Google Maps, Google +, Analytics, YouTube, and so on, apply for the address: Google API website.

Google Cloud Messaging for Android (GCM) is a service that helps developers send data from the server side to programs running on Android phones. This service provides a simple, lightweight mechanism that allows the server side to tell the mobile program to establish a direct connection to the server side to obtain updated programs or user data. The C2DM service can handle all Message Queuing problems and can send messages to target programs running on the target machine.

2 GCM Features

1 It allows third-party program server to send messages to their Android device.

2 GCM does not guarantee the delivery of messages and the order of messages.

3 Mobile-side programs do not need to run continuously to receive messages. The system wakes the program through intent broadcast when a new message arrives. Of course the program needs to be set up with proper broadcast receiver and permission.

4 It does not provide any user interface or other things to handle the message. C2DM simply passes the original message received to the program. This program provides a way to handle this message. For example, the program might throw a notification that shows a custom interface or just synchronizes the data.

5 GCM requires the phone to be running Android2.2 or later and to have Google Play Store, or to run an Android 2.2 virtual machine with Google API. However, you are not limited to deploying your program through the Google Play store.

6 It uses an existing connection for Google services. On the front 3.0 devices, this requires users to set up their Google account on their mobile device. Android 4.0.4 or higher for Google accounts is not required.

3 GCM in the use of the client

GCM The runtime requires three parameters:

Project number : get Project Number,project number from the API console to identify Android programs that are allowed to send messages to your phone during the registration phase. (used in client applications)

Application ID: Also known as API Key, registers a program to receive messages. This program is identified by manifest's package name. This ensures that the message is sent to the correct program. (used on the service side of the application program)

Registration ID: This ID is distributed by the C2DM server and is used to allow the program to receive messages. When the program has a registration ID, the ID is sent to the third-party program Server , and the third-party server uses the ID to identify each mobile phone registered to receive the message. In other words, the registration ID is bound to a program that runs on a phone.

Conditions:

Google User account: If GCM is to work, the phone will have at least one of the signed-in Google accounts, if the device is running Android version GCM less than 4.0.4, it is not required.

GCM Use the permissions you want to add:

1. Requires Android2.2 or later, so if your program does not work with GCM, add the following to the Androidmanifest file and replace the "XX" with the latest target SDK version number:

<uses-sdkandroid:minsdkversion= "8" android:targetsdkversion= "xx"/>

2. Add Networking permissions Android.permission.INTERNET

3. The device version below 4.0.4 need to add the following permissions, need Google account Android.permission.GET_ACCOUNTS permission

4. The processor can be guaranteed to get a message while sleeping Android.permission.WAKE_LOCK permission

5. Declare and use a custom permission to ensure that only this program can receive your GCM messages:

<permissionandroid:name= "My_app_package.permission.C2D_MESSAGE"

Android:protectionlevel= "Signature"/>

<uses-permissionandroid:name= "My_app_package.permission.C2D_MESSAGE"/>

This permission must be called: My_app_package.permission.C2D_MESSAG (Package name. PERMISSION.C2D_MESSAG, the package name is the package name defined in the manifest file), otherwise it will not function properly.

6. Add permission to receive GCM messages:

<uses-permissionandroid:name= "Com.google.android.c2dm.permission.RECEIVE"/>

7. Add the following broadcast receivers:

<receiver android:name= "Com.google.android.gcm.GCMBroadcastReceiver" android:permission= "Com.google.andro Id.c2dm.permission.SEND ">

<intent-filter>

<action android:name= "Com.google.android.c2dm.intent.RECEIVE"/>

<action android:name= "Com.google.android.c2dm.intent.REGISTRATION"/>

<category android:name= "My_app_package"/>

</intent-filter>

</receiver>

This broadcast Receiver is responsible for processing 2 intent from GCM (Com.google.android.c2dm.intent.RECEIVE and Com.google.android.c2dm.intent.REGISTRATION) , and is defined in the manifest file (not by encoding). Therefore, these intent can be received even if the program is not running.

By setting Com.google.android.c2dm.permission.SEND permissions, you can ensure that these intent can only be sent to this receiver via the GCM system framework (normal programs do not have permission to issue these intent).

Note that the Android:name in the Category tab must be replaced with the package name of your program (if the program is for a platform of 16 or higher minsdkversion then you do not need to have the category tag).

8. Add the following intent permissions:

<service android:name= ". Gcmintentservice "/>

Note: In the next step, the intent service will be called by Gcmbroadcastreceiver (provided by the GCM Library). It must be called my_app_package. Gcmintentservice, unless you use a subclass that overrides the Gcmbroadcastrecevier method as the name of the service.

GCM Key code:

The first step: Implement My_app_package. Gcmintentservice Class (secondary service is not a service in Android, but a mechanism in GCM)

Inherit the Gcmbaseintentservice class, and implement several methods as follows:

    • Onregistered (context context, String Regid): This method is called after receiving the registration intent, and the GCM-assigned registration ID is passed as a parameter to the device/application pair. Usually, you should send Regid to your server so that the server can send messages to the device based on this regid.
    • Onunregistered (context context, String Regid): Called when the device is logged off from GCM. Usually you should send regid to the server so that you can log out of the device.
    • OnMessage (context context, Intent Intent): When your server sends a message to GCM it will be called and GCM will send the message to the appropriate device. If the message contains payload data, their contents will be transmitted as intent extras.
    • OnError (context context, String ErrorID): This method is called when the device tries to register or log off, but GCM returns an error. Usually this method is to parse the error and fix the problem without doing anything else.
    • Onrecoverableerror (context context, String ErrorID): When the device tries to register or log off, but the GCM server is not valid. The GCM library retries the operation with a workaround, unless this method is overridden and returns false. This method is optional and will only be overridden if you want to display information to the user or cancel the retry operation.

Note: The above method runs in the thread of the intent service, so you have free access to the network without blocking the UI thread.

Step two: Code in the program activity

Add the following code to the OnCreate () method:

Gcmregistrar. Checkdevice (this);

Gcmregistrar. checkmanifest (this);

Regid=gcmregistrar. Getregistrationid (this);

if (Regid.equals ("")) {

Gcmregistrar. Register (this, globalcast. gcm_sender_id);

}

Else {

Try {

This is usually where you send the registered Registrationid to your server.

Uarwebservice muarwebservice=New uarwebservice (Activity. this, mvolley.requestqueue);

Muarwebservice.sendpushinfo (String. ValueOf(Constants. Customer. customerId), Regid);

} catch (Exception e) {

E.printstacktrace ();

}

}

The Checkdevice () method is used to verify that the device supports GCM and throws an exception if it is not supported (for example, the emulator does not contain Google APIs)

The Checkmanifest () method to verify that the program's manifest contains all the required descriptions to start writing Android programs (this method is only needed when you are developing the program, and you can remove it once the program is ready to be released).

Gcmregsistrar.register () registers the device by transmitting the sender_id that was obtained when registering the GCM. However, since the Gcmregistrar Singleton keeps track of the registration ID of all received registrations intent, you can first call the Gcmregistrar.getregistrationid () method to check whether the device is registered.

4 GCM on the service side of the simple use

The key code is as follows:

Import com.google.android.gcm.server.*;

Sender sender = new Sender (Myapikey);

Message message = new Message.builder (). build ();

Multicastresult result = sender.send (message, devices, 5);

The code snippet above implements the following work:

    • Create a Sender object with your project's API key.
    • Create a message with the obtained registration ID (the builder of the message also has a way to set all the message parameters, such as collapse key and payload data).
    • Send this message (if the GCM server is not valid, there are 5 resend opportunities) and save the response to result.
    • It is now necessary to parse the response and take appropriate action on the following conditions:
    • If the message is created, but the result returns a recognized registration ID, then the current registration ID needs to be replaced with this recognized ID.
    • If the error returned is notregistered, then the registration ID needs to be removed because the device does not have the program installed.

GCM Message Push

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.