gpt4 book ai didi

java - GCM : How to send heartbeat to GCM server

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:04 27 4
gpt4 key购买 nike

我想从我的应用程序向 GCM 服务器发送一个心跳信号,以便连接保持有效。

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

提前致谢!

最佳答案

如何发送心跳

这个类可以发送正确的 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);
}

}

如果你只是想发送心跳你可以在一个Activity中执行以下操作

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

我认为您不需要为此设置任何额外的权限,但这是我在 list 中拥有的 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 注入(inject)的 alarmmanger 和 pendingintent

@Inject AlarmManager alarmManager;
@Inject PendingIntent gcmKeepAlivePendingIntent;


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

这是 Dagger 模块的部分,它提供警报管理器和未决 Intent 。有几种方法可以让警报管理器定期调用一个方法,所以假设你不使用 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);
}

关于java - GCM : How to send heartbeat to GCM server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471141/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com