GCM:如何将心跳发送到GCM服务器

时间:2014-12-14 16:06:07

标签: java android google-cloud-messaging heartbeat

我想从我的应用程序向GCM服务器发送心跳,因此连接将保持活动状态。

我该怎么做,我怎么知道我的GCM服务器的URL ??

提前致谢!!

1 个答案:

答案 0 :(得分:7)

如何发送心跳

这个类可以发送正确的意图

   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);
        }

    }

如果您只想发送心跳,可以在活动中执行以下操作

GcmKeepAlive gcmKeepAlive = new GcmKeepAlive(this);
gcmKeepAlive.broadcastIntents();

我认为您不需要为此设置任何其他权限,但以下是我在清单中的gcm相关权限

<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" />

定期发送心跳的一种方法

如果你想定期发送,我就是这样做的:

    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();

        }

    }

我还有一个服务,它有一个Dagger注入的alarmmanger和pendingintent

@Inject AlarmManager alarmManager;
@Inject PendingIntent gcmKeepAlivePendingIntent;


alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, 4*60*1000, gcmKeepAlivePendingIntent);

这是Dagger模块中提供警报管理器和待处理意图的部分。 警报管理器有多种方法可以定期调用方法,因此假设您不使用Dagger,您仍然可以提取相关部分。您的问题是如何发送心跳,而不是如何使用警报管理器。有很多答案已经如此搜索。

@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);
}