java – GCM:如何将心跳发送到GCM服务器
发布时间:2020-12-15 04:24:12 所属栏目:Java 来源:网络整理
导读:我想从我的应用程序向GCM服务器发送心跳,因此连接将保持活动状态. 我怎么能这样做,我怎么知道我的GCM服务器的URL? 提前致谢!! 解决方法 如何发送心跳 这个类可以发送适当的意图 public class GcmKeepAlive { protected CountDownTimer timer; protected C
我想从我的应用程序向GCM服务器发送心跳,因此连接将保持活动状态.
我怎么能这样做,我怎么知道我的GCM服务器的URL? 提前致谢!! 解决方法
如何发送心跳
这个类可以发送适当的意图 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模块中提供警报管理器和待处理意图的部分. @Provides PendingIntent provideGcmKeepAlivePendingIntent() { System.out.println("pending intent provider"); Intent gcmKeepAliveIntent = new Intent("com.gmail.npnster.first_project.gcmKeepAlive"); return PendingIntent.getBroadcast(mContext,gcmKeepAliveIntent,PendingIntent.FLAG_CANCEL_CURRENT); } @Provides AlarmManager provideGcmKeepAliveAlarmManager() { return (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |