GCM: how to send heartbeat to GCM server
How to send heartbeat
This class can send the correct intent
public class GcmKeepAlive {
protected CountDownTimer timer;
protected Context mContext;
protected Intent gTalkHeartBeatIntent;
protected Intent mcsHeartBeatIntent;
public GcmKeepAlive(Context context) {
mContext = context;
gTalkHeartBeatIntent = new Intent(
"com.google.android.intent.action.GTALK_HEARTBEAT");
mcsHeartBeatIntent = new Intent(
"com.google.android.intent.action.MCS_HEARTBEAT");
}
public void broadcastIntents() {
System.out.println("sending heart beat to keep gcm alive");
mContext.sendBroadcast(gTalkHeartBeatIntent);
mContext.sendBroadcast(mcsHeartBeatIntent);
}
}
if you just want to send a heartbeat you can do the following in Activity
GcmKeepAlive gcmKeepAlive = new GcmKeepAlive(this);
gcmKeepAlive.broadcastIntents();
I don't think you need to set additional permissions for this, but here are the gcm related permissions I have in my manifest
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name=your_package_name.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="your_package_name.permission.C2D_MESSAGE" />
One way to send heartbeats on a regular basis
If you want to send them on a regular basis, here's how I do it:
public class GcmKeepAliveBroadcastReceiver extends BroadcastReceiver {
private GcmKeepAlive gcmKeepAlive;
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("inside gcm keep alive receiver");
gcmKeepAlive = new GcmKeepAlive(context);
gcmKeepAlive.broadcastIntents();
}
}
I also have a service that has a dagger injected with an alarm injected and waiting for a response
@Inject AlarmManager alarmManager;
@Inject PendingIntent gcmKeepAlivePendingIntent;
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, 4*60*1000, gcmKeepAlivePendingIntent);
Here is a section of the Dagger module that provides an alert dispatcher and pending intent. There are several ways for the alarm manager to call the method periodically, so assuming you are not using the dagger, you can still pull out the relevant parts. Your question was how to send the heartbeat, not how to use the alarm manager. There are many answers to this, so search about this.
@Provides PendingIntent provideGcmKeepAlivePendingIntent() {
System.out.println("pending intent provider");
Intent gcmKeepAliveIntent = new Intent("com.gmail.npnster.first_project.gcmKeepAlive");
return PendingIntent.getBroadcast(mContext, 0, gcmKeepAliveIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}
@Provides AlarmManager provideGcmKeepAliveAlarmManager() {
return (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
}
source to share