http://blog.csdn.net/fanst_/article/details/50732026
MyGcmListenerService.java
GCM接收监听服务类,接收GCM发过来的通知消息,并显示到手机状态栏中。
RegistrationIntentService.java
向GCM服务器进行设备注册,获取注册token,该token会作为通知消息接收设备的标识,该类中还进行了topics的订购。
MyInstanceIDListenerService.java
接收token更新通知,收到通知后会重新通过RegistrationIntentService获取新的token。
GcmSender.java
推送消息发送类,通过该类向GCM发送HTTP消息,GCM再推送给终端设备。该类并不是必需的,下文也提到了,可以通过Postman等工具直接发送HTTP消息。
A Google Cloud Messaging (GCM) Android client is a client app that runs on an Android device. To write your client code, we recommend that you use the GoogleCloudMessaging
API and Android Studio with Gradle.
Here are the requirements for running a GCM Android client:
- GCM requires devices running Android 2.2 or higher that also have the Google Play Store application installed, or an emulator running Android 2.2 with Google APIs. Note that you are not limited to deploying your Android applications through Google Play Store.
- However, if you want to continue to use new GCM features that are distributed through Google Play Services, the device must be running Android 2.3 or higher, or you can use an emulator running Android 2.3 with Google APIs.
- On Android devices, GCM uses an existing connection for Google services. For pre-3.0 devices, this requires users to set up their Google accounts on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.
A full GCM implementation requires both a client implementation and a server implementation. For more information about implementing the server side, see About GCM Connection Server.
The following sections walk you through the steps involved in writing a GCM client-side application on Android. At a minimum, a GCM client app must include code to register (and thereby get a registration token), and a receiver to receive messages sent by GCM.
For existing apps that extend aWakefulBroadcastReceiver
, Google recommends migrating to
GCMReceiver
and
GcmListenerService
. To migrate:
- In the app manifest, replace your
GcmBroadcastReceiver
with "com.google.android.gms.gcm.GcmReceiver", and replace the current service declaration that extendsIntentService
to the newGcmListenerService
- Remove the
BroadcastReceiver
implementation from your client code - Refactor the current
IntentService
service implementation to useGcmListenerService
Create an API project
New Cloud Messaging projects must create a Firebase project in the Firebase console. In this process, you'll generate a configuration file and credentials for your project.
- Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
- Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
- When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
- At the end, you'll download a
google-services.json
file. You can download this file again at any time. - If you haven't done so already, copy this into your project's module folder, typically
app/
.
Add the configuration file to your project
The Google Services plugin for Gradle parses configuration information from the google-services.json
file. Add the plugin to your project by updating your top-level build.gradle
and your app-level build.gradle
files as follows:
- Add the dependency to your project-level
build.gradle
: - Add the plugin to your app-level
build.gradle
:
Set Up Google Play Services
To write your client application, use the GoogleCloudMessaging
API. To use this API, you must set up your project to use the Google Play services SDK, as described in Set up Google Play Services SDK.
When you add the GCM Play Services library to your project, be sure to add it with resources, as described in Set up Google Play Services SDK. The key point is that you must reference the library—simply adding a .jar
file to your project will not work. If you're using Android Studio, this is the string to add to the dependency
section of your application's build.gradle
file:
dependencies {This example shows how to reference the GCM-specific library, which is the only library you'll need to support GCM app development. Use this instead of the comprehensive Play Services library, and make sure you are referencing the newest version.
compile "com.google.android.gms:play-services-gcm:10.2.0"
}
Edit Your Application's Manifest
Add the following to your application's manifest:
- A declaration of
GcmReceiver
, which handles messages sent from GCM to your application. Because this service needs permission to receive messages from GCM, addcom.google.android.c2dm.permission.SEND
to the receiver. - A declaration of
GcmListenerService
, which enables various aspects of handling messages such as detecting different downstream message types, determining upstream send status, and automatically displaying simple notifications on the app’s behalf. - A service that extends
InstanceIDListenerService
, to handle the creation, rotation, and updating of registration tokens. - Optionally, the
android.permission.WAKE_LOCK
permission if the application needs to keep the processor from sleeping when a message is received. - If the GCM feature is critical to the Android application's function, be sure to set
android:minSdkVersion="8"
or higher in the manifest. This ensures that the Android application cannot be installed in an environment in which it could not run properly.
Here is an example manifest that supports GCM:
<manifest package="com.example.gcm" ...>If you want to support pre-4.4 KitKat devices, add the following action to the intent filter declaration for the receiver:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application ...>
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service
android:name="com.example.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="com.example.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name="gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService"
android:exported="false">
</service>
</application>
</manifest>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
Check for Google Play Services APK
Apps that rely on the Play Services SDK should always check the device for a compatible Google Play services APK before accessing Google Play services features. It is recommended to do this in two places: in the main activity's onCreate()
method, and in its onResume()
method. The check in onCreate()
ensures that the app can't be used without a successful check. The check in onResume()
ensures that if the user returns to the running app through some other means, such as through the back button, the check is still performed. If the device doesn't have a compatible Google Play services APK, your app can call GooglePlayServicesUtil.getErrorDialog()
to allow users to download the APK from the Google Play Store or enable it in the device's system settings. For a code example, see Set up Google Play Services SDK.
Obtain a registration token
An Android application needs to register with GCM connection servers before it can receive messages. When an app registers, it receives a registration token and sends it to the app server. The client app should store a boolean value indicating whether the registration token has been sent to the server.
Google provides the Instance ID API to handle the creation and updating of registration tokens. To use this API, includeInstanceIDListenerService
in the manifest:
<service android:name="[.MyInstanceIDService]" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
To obtain a token, call instanceID.getToken
, providing the app server's sender ID and setting the scope to GoogleCloudMessaging.INSTANCE_ID_SCOPE
. Do not call this method in the main thread; instead, use a service that extends IntentService as shown:
public class RegistrationIntentService extends IntentService {
// ...
@Override
public void onHandleIntent(Intent intent) {
// ...
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// ...
}
// ...
}
Once you've received your registration token, make sure to send it to your server.
The listener service's onTokenRefresh
method should be invoked if the GCM registration token has been refreshed:
@Override
public void onTokenRefresh() {
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
Once onTokenRefresh
is called, use InstanceID.getToken()
to get a new registration token, and then send the new token to your app server.
See the Instance ID API reference for full detail on this API.
GCM register() has been deprecated. Use InstanceID to perform general GCM registration management.Next steps
Once the client app is connected, you are ready to start receiving downstream messages and sending upstream messages. For more information about your options with GCM, see also guides for topic messaging and device group messaging as well as the reference information for both client and server APIs.
- 1
- 2
- 1
- 2