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

Ita*_*tay 3 java android heartbeat google-cloud-messaging

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

我怎么能这样做,我怎么知道我的GCM服务器的URL?

提前致谢!!

nPn*_*nPn 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);
        }

    }
Run Code Online (Sandbox Code Playgroud)

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

GcmKeepAlive gcmKeepAlive = new GcmKeepAlive(this);
gcmKeepAlive.broadcastIntents();
Run Code Online (Sandbox Code Playgroud)

我不认为您需要为此设置任何其他权限,但这是我在清单中的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" />
Run Code Online (Sandbox Code Playgroud)

一种定期发送心跳的方法

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

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

        }

    }
Run Code Online (Sandbox Code Playgroud)

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

@Inject AlarmManager alarmManager;
@Inject PendingIntent gcmKeepAlivePendingIntent;


alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, 4*60*1000, gcmKeepAlivePendingIntent);
Run Code Online (Sandbox Code Playgroud)

以下是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);
}
Run Code Online (Sandbox Code Playgroud)