GCM sends and receives Message Client Server, Client

Source: Internet
Author: User
Tags android sdk manager

GCM Transfer Parameters

Recently, I spent a lot of time doing GCM. I encountered many problems, so I made a detailed record to make it easier for you to use it. however, I tried GCM, which is not easy to use in China. if you develop a program outside China, it would be a good choice to use GCM. in China, it is basically not as good as sending ten requests. The other nine requests are blocked by the Great Wall firewall.

The most authoritative GCM of Google is, of course, the official website. at the beginning, I followed the official website and used online materials in some places to improve my skills. the red area indicates the important area.

1. Preparations 1. Create a Google API project:

Open the Google API console page. Https://code.google.com/apis/console)

If you have not created an API project, this page will prompt you to do so.

 

If you already have a project, the first page you see will beDashboardPage. From there, you can open the project drop-down menu (upper left corner) and selectOther> CreateA new project.

Click Create project.

2 enable GCM Service 3 get a Server API key

To get an API key: on the Google API console homepage, after selecting a project, there is Overview on the right. The Google interface has been updated, but many of them are still the original interfaces on the Internet, I took a detour. the following is the latest page.

 

As shown above. go to OverView ==> API & auth ==> Credentials ==>. The following screen is displayed, and the Public API access is shown in the middle column, have you seen the following Key for server applications? There is an API key in it,

Note:If you do not have key for server applications, remember to use Server application. Not the client Application above. ClickGenerate new key. A new key will be created, and the previous key will remain valid for the next 24 hours. If you want to invalidate the previous key immediately (for example, you think it has been cracked), clickDelete key.

4. Install the auxiliary Library

Before performing the steps described in the following sections, make sure that the auxiliary library has been installed. Open Android SDK Manager and installExtras> Google Cloud Messaging for Android Library. This willYOUR_SDK_ROOTCreate a gcm folder under the/extras/google/directory, which contains: gcm-client, gcm-demo-appengine, gcm-demo-client, gcm-demo-server, and gcm-server subdirectory.

Note:The SDK Manager version must be r20 or later, and the GCM library cannot be found in earlier versions. So start eclipse and upgrade ADT.

 

Several Libraries under Extra ==>, after installation, enter the hard disk this is my path: E: \ android \ adt-bundle-windows-x86-20130729 \ sdk \ extras \ google \ gcm

There are gcm-client, gcm-server, samples, and so on. There is a required rack package.

2 GCM Principle

After the preparation is completed, let's talk about the principle:

3. Start Program Creation

According to the above analysis, we should first establish an acceptor: Below is my direct use of online materials. If you think it is very complicated, you can take a look at my example and compare it, this understanding is more in-depth.

Download: Client: Step 1: Copy gcm. jar to the classpath directory of the program.

Before writing a program, copy the gcm. jar file in the gcm-client/dist directory under the SDK directory to the classpath of the program.

Step 2: follow these steps to change the AndroidManifest. xml file of the project:

1. GCM requires Android2.2 or a later version, so if your program cannot work normally without relying on GCM, add the following content to the AndroidManifest file, replace "xx" with the latest target SDK version:

<Uses-sdkandroid: minSdkVersion = "8" android: targetSdkVersion = "xx"/>

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

<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_mession (package name. permission. c2d_mession, the package name is defined in the manifest file). Otherwise, the package cannot run normally.

Note:If your program is targeting a system of Version 4.1 or later (that is, minSdkVersion 16), you do not need this permission.

3. Add the permission to receive GCM messages:

<Uses-permissionandroid: name = "com. google. android. c2dm. permission. RECEIVE"/>

4. Add the following broadcast receivers:

 

<Cycler android: name = "com. google. android. gcm. GCMBroadcastReceiver" android: permission = "com. google. android. 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>

</Cycler>

This Broadcast receiver is responsible for processing two Intent (com. google. android. c2dm. intent. RECEIVE and com. google. android. c2dm. intent. REGISTRATION), and must be defined in the manifest file (not implemented by encoding ). Therefore, these intents can even be received when the program is not running. By setting the com. google. android. c2dm. permission. SEND permission, you can ensure that these intents can only be sent to the receiver through the GCM System Framework (normal programs do not have the permission to issue these intents ).

Note that the android: name in the category label must be replaced with the package name of your program (if the program is for a platform of 16 or higher minSdkVersion, you do not need to have the category label ).

5. Add the following Intent services:

<Service android: name = ". GCMIntentService"/>

In the next step, this 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 overwrites the GCMBroadcastRecevier method as the name of this service.

Step 3: implement the my_app_package.GCMIntentService class

The following describes how to implement the my_app_package.GCMIntentService class and override the following callback methods (these methods will be called by GCMBroadcastReceiver ):

  • OnRegistered (Context context, String regId): This method is called after Intent registration is received. The registered ID assigned by GCM is passed as a parameter to the device/application. Generally, you should send a regid to your server so that the server can send messages to the device based on this regid.
  • OnUnregistered (Context context, String regId): this parameter is called when the device logs out of GCM. Generally, you should send the 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 corresponding device. If the message contains the payload data, its content will be transmitted as the extras of the Intent.
  • OnError (Context context, String errorId): This method is called when the device attempts to register or log out, But GCM returns an error. This method is usually used to analyze errors and fix problems without doing anything else.
  • OnRecoverableError (Context context, String errorId): When the device attempts to register or log out, but the GCM server is invalid. The GCM library uses an emergency solution to retry operations, unless this method is overwritten and false is returned. This method is optional and will be overwritten only when you want to display information to the user or cancel the retry operation.

Note:The above method runs in the Intent service thread, so you can freely access the network without blocking the UI thread.

Step 4: implement the main Activity of your program

Add the following Import Statement to the main activity of your program:

Import com. google. android. gcm. GCMRegistrar;

Add the following code in the onCreate () method:

GCMRegistrar. checkDevice (this );

GCMRegistrar. checkManifest (this );

Final String regId = GCMRegistrar. getRegistrationId (this );

If (regId. equals ("")){

GCMRegistrar. register (this, SENDER_ID );

} Else {

Log. v (TAG, "Already registered ");

}

The checkDevice () method is used to verify whether the device supports GCM. If not, an exception is thrown (for example, the simulator does not contain Google APIs ). Similarly, the checkManifest () method is used to verify that the manifest of the program contains all the required descriptions in the preparation of the Android Program (this method is only required when developing the program; once this program is ready for release, you can remove it ).

Once these health checks are completed, you can call GCMRegsistrar. register () to register the device by sending the SENDER_ID obtained during GCM registration. However, the GCMRegistrar Singleton keeps track of all registered Intent IDs, so you can call the GCMRegistrar. getRegistrationId () method to check whether the device is registered.

Note:The device may have been successfully registered to GCM but failed to send the registration ID to your server. In this case, you should try again. Please refer to the advanced topic for more details on how to handle this situation.

Here is the program I have prepared: client:

The following is my code:

1. as shown in, there is a problem to be aware of. The first SENDER_ID is the ProjectID you allocated when you set up the project on Google. It is marked with a red background color. projectID.

This program means:

Private final BroadcastReceiver mHandleMessageReceiver =
New BroadcastReceiver (){
@ Override
Public void onReceive (Context context, Intent intent ){
String newMessage = intent. getExtras (). getString (EXTRA_MESSAGE );
Intent = GCMIntentService. intentDefault;
NewMessage + = intent. getStringExtra ("score ");
NewMessage + = intent. getStringExtra ("time ");
MDisplay. append (newMessage + "\ n ");
}};

When the client receives the information, it does not actually execute it but @ Override in GCMIntentService. java.
Protected void onMessage (Context context, Intent intent ){
Log. I (TAG, "Received message ");
String message = getString (R. string. gcm_message );


DisplayMessage (context, message );

// Notifies user
GenerateNotification (context, message );
// String newMessage = intent. getExtras (). getString (EXTRA_MESSAGE );
GCMIntentService. intentDefault = intent;
// NewMessage + = intent. getStringExtra ("score ");
// NewMessage + = intent. getStringExtra ("time ");
// DemoActivity. mDisplay. append (newMessage + "\ n ");
}

So when you need to get the passed parameters, for example:

NewMessage + = intent. getStringExtra ("score ");
NewMessage + = intent. getStringExtra ("time ");

The Intent in the onMessage () method in GCMIntentService must be retrieved. The Intent in mHandleMessageReceiver is not the original Intent.

Okay, we have finished the client,

Let's take a look at the server. Code: Server.

The server is actually a simple class name for passing data: GCMServerClass, which references the shelf package in GCMServerLib. Here, GCMSeverLib is of no practical use, to store the racks in GCMServerClass, let's take a look at GCMServerClass.

 

In the figure, there is an apiKey. This is the Sever API key generated by the project. What I use is AIzaSyAmCeG5SHgiJRqXWM4TyS2LiQhAsKHGOVA.

There is also a deviceRegId that I mentioned above in red.

The regId generated during client registration;

Format of passing parameters: new Message. Builder (). addData ("score", "abcd"). addData ("time", "time3"). build ();

In this way, You may click Run as... in the Console.

This problem is caused by Google's blockout. The GCM is unstable after multiple attempts. It should be used well in foreign countries. It will be better if there are three attempts in 10 attempts, similar to: 0: 1387799674664999% 2adac3a0f9fd7mcm indicates no problem.

:

 

Congratulations, the server is connected. In the connection, when the server is finished, the onMessage () on the client should be immediately matched. In this way, the values of the two parameters are obtained.

Of course, the server sends data not only by class, but also by many methods. I have tried another method before, that is, using Google's poster.

Address: Google Poster

Installation Procedure ==> Open google explorer ==> tools ==> extensions ==>

 

 

 

After downloading the plug-in, drag it in directly. After the plug-in is installed, there is a P on the right side:

 

 

 

Write all the data on the server to poster:

Write method:
Open poster and enter the address information:
URL input:

Headers:

Name ::

Value :;

Click Add/Change:

Name ::

Value:

Content Body: input:
{"Data ":{
"Score": "5x1 ",
"Time": "15: 10"
},
"Registration_ids": [""]
}

The registration_ids is the regId generated on the client just now. It works the same way as the server.

Then click the POST button. If Google is good at service, the message is sent directly, which is the same as that on the server. Then, the onMessage on the client will receive the message.

Finished.

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.