A library that makes Google Cloud Messaging between Android Devices simple.
-
Copy gcm package into your project and add this config to the 'app' directory.
-
Permissions: (Notice where you should insert you package name)
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<permission android:name="<YOUR PACKAGE NAME>.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
<uses-permission android:name="<YOUR PACKAGE NAME>.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
- Registrations (in manifest file):
<service android:name=".gcm.GcmRegistrationService"/>
<service android:name=".gcm.GcmMessageListener" android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
<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="<YOUR PACKAGE NAME HERE>"/>
</intent-filter>
</receiver>
And you should be good to go.
- Implement the "GcmHandler" callback class and its methods. Can be implemented by an Activity.
public class MainActivity implements GcmHandler
- Create a "Gcm" instance:
Gcm gcm = new Gcm(context, gcmHandler);
2.1) Make sure to set your API key: (the one you got from "How to install: #1)
gcm.setApiKey(myApiKey);
This is important to do right after creating an instance.
- To obtain the unique key of this device, needed to send messages to it, use:
gcm.requestDeviceToken();
The token will we requested and returned to the GcmHandler's onGcmTokenReceived()
method.
The token should behave like a "Phone number" and generaly does not change.
- Now you can send Messages!
gcm.sendMessage(toDeviceToken, bundledMessage)
When the message is sent, the GcmHandler's onGcmMessageSent()
is called.
Messages you receive will go to the GcmHandler's onGcmMessageReceived()
.