GCM Method for Android message push (1)

Source: Internet
Author: User
Tags android sdk manager

 
Click "Create project" to guide you through creating the first project. If you have created a project before, you will not see this prompt. You will see a panel. Click the drop-down menu in the upper left corner and select "Other projects"-"Create". This will guide you through creating a project. Your browser address will be shown as https://code.google.com/apis/lele/#project:812216982441. Note # project: the following number is 812216982441, which will be used as the identification number in the GCM service to register with the Google server on the client. The above is the first step in preparation.

2. Activate Your GCM service.

On the Google Api console page, select "Services", open the switch in "Google Cloud Messaging for Android", and accept the Protocol to activate GCM under your account.

Third: Obtain the API Key

On the console page, select "API Access ". Click "Create New Server Key" and directly click "Create" on the following interface. An Api Key is generated, which is used to verify the sender.

Fourth, your computer needs some packages necessary for GCM services. These packages can be downloaded and installed in the Android SDK Manager. The updated package is Google Cloud Messaging for Android, which is included in the Extras extension. After installation, In the \ extras \ google \ gcm directory where the sdk is located, you will see that gcm's tools and packages used for sending, receiving, and other operations are included here.

You can use eclipse to directly import these projects and import several packages. Based on these class files, we create calls to them. The preparation is complete. Next, let's talk about how to use it. (Note: In preparation, if the Android device does not have the Google Play Services package, you need to add Step 4 to download the Google play service package and install it on your mobile phone or tablet)

It should be noted that the GMC method does not have strict clients and servers. It only requires Android applications to receive messages, and the sender can be any program. It can be in the same Android app on your own server, or it can be just a main function. However, the classes and environments to be used must be set up separately.

You can use the GCMRegistrar and Sender classes to register and send messages on the client. These two classes are in the gcm service package we just downloaded. (In the Google play Service Pack google-play-services.jar package, there is a GoogleCloudMessaging class that can also provide methods for registering clients and sending messages. However, I read the official documentation, which is similar to the previous method. This method is not mentioned here .)

 


The above preparations have been completed. The following describes how to implement the Code:

 


First, let's talk about registering a service on the client. First, add three GCM/C2DM permissions and necessary network access permissions to the AndroidManifest. xml file. The complete file is provided later.

 


Create an android service named GCMIntentService, inherit the abstract class GCMBaseIntentService, and implement several methods. Remember to declare the service in the configuration file. In particular, this service must be named GCMIntentService and put under the application package name. Because the GCM mechanism uses this service by default, and does not provide a way to replace it with other services.

GCMIntentService class:


[Java]
Public class GCMIntentService extends GCMBaseIntentService {
Public static final String SENDERID = "812216982441 ";

Public GCMIntentService (){
Super (SENDERID );
}
 
@ Override
Protected void onError (Context arg0, String arg1 ){
Log. v ("GCMIntentService", "onError error ");
}
 
@ Override
Protected void onMessage (Context arg0, Intent arg1 ){
Log. v ("GCMIntentService", "New Message received:" + arg1.getStringExtra ("mine "));
Final String info = arg1.getStringExtra ("mine ");
Handler handler = new Handler (Looper. getMainLooper ());
Handler. post (new Runnable (){

@ Override
Public void run (){
Toast. makeText (getBaseContext (), "New Message received:" + info, Toast. LENGTH_LONG). show ();
}
});
}
 
@ Override
Protected void onRegistered (Context arg0, String arg1 ){
Log. v ("GCMIntentService", "onRegistered registration completed ");
}
 
@ Override
Protected void onUnregistered (Context arg0, String arg1 ){
Log. v ("GCMIntentService", "onUnregistered deregister registration ");
}
 
}

Public class GCMIntentService extends GCMBaseIntentService {
Public static final String SENDERID = "812216982441 ";
 
Public GCMIntentService (){
Super (SENDERID );
}

@ Override
Protected void onError (Context arg0, String arg1 ){
Log. v ("GCMIntentService", "onError error ");
}

@ Override
Protected void onMessage (Context arg0, Intent arg1 ){
Log. v ("GCMIntentService", "New Message received:" + arg1.getStringExtra ("mine "));
Final String info = arg1.getStringExtra ("mine ");
Handler handler = new Handler (Looper. getMainLooper ());
Handler. post (new Runnable (){

@ Override
Public void run (){
Toast. makeText (getBaseContext (), "New Message received:" + info, Toast. LENGTH_LONG). show ();
}
});
}

@ Override
Protected void onRegistered (Context arg0, String arg1 ){
Log. v ("GCMIntentService", "onRegistered registration completed ");
}

@ Override
Protected void onUnregistered (Context arg0, String arg1 ){
Log. v ("GCMIntentService", "onUnregistered deregister registration ");
}

}
These methods combine the GCM mechanism. Do not misunderstand that they are Android services.

OnError: called when an error occurs when registering a client or canceling registration.
OnMessage: called when the client receives the message.

OnRegistered: registration is complete.

OnUnregistered: the registration is canceled.

"Constant" SENDERID is the value obtained when you create a project on the console page.

After the service class is created, you can register it. The following are the registered code snippets that can be executed directly in the onCreate method of Activit.


[Java] view plaincopyprint? Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );

GCMRegistrar. checkDevice (this );
GCMRegistrar. checkManifest (this );
Final String regId = GCMRegistrar. getRegistrationId (this );
If (regId. equals ("")){
GCMRegistrar. register (this, GCMIntentService. SENDERID );
Log. v (TAG, "New Device:" + GCMRegistrar. isRegistered (this) + GCMRegistrar. getRegistrationId (this ));
} Else {
Log. v (TAG, "Already registered ");
}
// Unregister after clicking and do not receive messages
Button btn = (Button) findViewById (R. id. unregist_btn );
Btn. setOnClickListener (new OnClickListener (){

@ Override
Public void onClick (View v ){
GCMRegistrar. unregister (getBaseContext ());
}
});

}

Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );

GCMRegistrar. checkDevice (this );
GCMRegistrar. checkManifest (this );
Final String regId = GCMRegistrar. getRegistrationId (this );
If (regId. equals ("")){
GCMRegistrar. register (this, GCMIntentService. SENDERID );
Log. v (TAG, "New Device:" + GCMRegistrar. isRegistered (this) + GCMRegistrar. getRegistrationId (this ));
} Else {
Log. v (TAG, "Already registered ");
}
// Unregister after clicking and do not receive messages
Button btn = (Button) findViewById (R. id. unregist_btn );
Btn. setOnClickListener (new OnClickListener (){

@ Override
Public void onClick (View v ){
GCMRegistrar. unregister (getBaseContext ());
}
});

}
CheckDevice () checks the system version and whether google service frame is installed. Otherwise, an exception is thrown. (The GCM service must be installed with a Google service package and the system version is 2.2 or later)

CheckManifest () checks whether the AndroidManifest. xml file has the required permissions for configuration, checks whether the broadcast receiver has the correct permissions and filters, and whether it can normally receive broadcasts. Otherwise, an exception is thrown.


Register () registers a GCM service. It starts a service named com. google. android. c2dm. intent. REGISTER with the action name. Note that this is the real GCM service, and the one we created earlier is not actually a GCM service, but a service callback provided by the entire GCM service mechanism.

Complete AndroidManifest. xml file:


[Html] view plaincopyprint? <? Xml version = "1.0" encoding = "UTF-8"?>
<Manifest
Xmlns: android = "http://schemas.android.com/apk/res/android"
Package = "com. ives. androidgcmclient"
Android: versionCode = "1"
Android: versionName = "1.0" type = "codeph" text = "/codeph">
<Uses-sdk
Android: minSdkVersion = "8"
Android: targetSdkVersion = "15"/>
<Permission
Android: name = "com. ives. androidgcmclient. permission. C2D_MESSAGE"
Android: protectionLevel = "signature"/>
<Uses-permission
Android: name = "com. ives. androidgcmclient. permission. C2D_MESSAGE"/>
<Uses-permission
Android: name = "com. google. android. c2dm. permission. RECEIVE"/>
<Uses-permission
Android: name = "android. permission. INTERNET"/>
<Uses-permission
Android: name = "android. permission. GET_ACCOUNTS"/>
<Uses-permission
Android: name = "android. permission. WAKE_LOCK"/>
<Uses-permission
Android: name = "android. permission. CHANGE_NETWORK_STATE">
</Uses-permission>
<Uses-permission
Android: name = "android. permission. CHANGE_WIFI_STATE">
</Uses-permission>
<Uses-permission
Android: name = "android. permission. ACCESS_NETWORK_STATE">
</Uses-permission>
<Uses-permission
Android: name = "android. permission. ACCESS_WIFI_STATE"/>
<Application
Android: allowBackup = "true"
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name"
Android: theme = "@ style/AppTheme">
<Activity
Android: name = "com. ives. androidgcmclient. MainActivity"
Android: label = "@ string/app_name">
<Intent-filter>
<Action
Android: name = "android. intent. action. MAIN"/>
 
<Category
Android: name = "android. intent. category. LAUNCHER"/>
</Intent-filter>
</Activity>
 
<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 = "com. ives. androidgcmclient"/>
</Intent-filter>
</Cycler>
<Service
Android: name = ". GCMIntentService"/>
</Application>
 
</Manifest>

<? Xml version = "1.0" encoding = "UTF-8"?>
<Manifest
Xmlns: android = "http://schemas.android.com/apk/res/android"
Package = "com. ives. androidgcmclient"
Android: versionCode = "1"
Android: versionName = "1.0" type = "codeph" text = "/codeph">
<Uses-sdk
Android: minSdkVersion = "8"
Android: targetSdkVersion = "15"/>
<Permission
Android: name = "com. ives. androidgcmclient. permission. C2D_MESSAGE"
Android: protectionLevel = "signature"/>
<Uses-permission
Android: name = "com. ives. androidgcmclient. permission. C2D_MESSAGE"/>
<Uses-permission
Android: name = "com. google. android. c2dm. permission. RECEIVE"/>
<Uses-permission
Android: name = "android. permission. INTERNET"/>
<Uses-permission
Android: name = "android. permission. GET_ACCOUNTS"/>
<Uses-permission
Android: name = "android. permission. WAKE_LOCK"/>
<Uses-permission
Android: name = "android. permission. CHANGE_NETWORK_STATE">
</Uses-permission>
<Uses-permission
Android: name = "android. permission. CHANGE_WIFI_STATE">
</Uses-permission>
<Uses-permission
Android: name = "android. permission. ACCESS_NETWORK_STATE">
</Uses-permission>
<Uses-permission
Android: name = "android. permission. ACCESS_WIFI_STATE"/>
<Application
Android: allowBackup = "true"
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name"
Android: theme = "@ style/AppTheme">
<Activity
Android: name = "com. ives. androidgcmclient. MainActivity"
Android: label = "@ string/app_name">
<Intent-filter>
<Action
Android: name = "android. intent. action. MAIN"/>

<Category
Android: name = "android. intent. category. LAUNCHER"/>
</Intent-filter>
</Activity>

<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 = "com. ives. androidgcmclient"/>
</Intent-filter>
</Cycler>
<Service
Android: name = ". GCMIntentService"/>
</Application>

</Manifest>

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.