我知道这些方法已被弃用,但由于新的GCM API似乎有问题,我将恢复这些方法,直到谷歌推出稳定版本。
我们在清单中宣布这个接收器。
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.myApp" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
我们在GCMIntentService类中有onMessage()方法。
@Override
protected void onMessage(Context context, Intent intent)
{
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("msg");
}
此外,我遵循的示例使用以下内容。
registerReceiver(mHandleMessageReceiver, new IntentFilter("intent_filter_string"));
与以下课程相关联。
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String newMessage = intent.getExtras().getString("data");
}
};
在onPause中未注册。
感谢答案。
答案 0 :(得分:1)
为什么我们需要创建此广播接收器?
In some cases you might be interested in updating the UI if the app is running.
So you create a broadcast receiver at runtime and unregister it when the app
goes into background.
我们不能在清单中这样做吗?
Yes, you can do it in manifest too.
GCMIntentService类中的onMessage()是否已经涵盖了这一点?
GCMIntentService extends GCMBaseIntentService. So any message coming from gcm,
will first be recieved in the onMessage of the GCMIntentService.
Its upto you to decide how you handle the message.
You can create a notification or send a broadcast to your custom broadcast
receivers and update the UI when the app is running.
Pending Intent扮演什么角色?
根据docs
A PendingIntent itself is simply a reference to a token maintained by the system
describing the original data used to retrieve it. This means that, even if its
owning application's process is killed, the PendingIntent itself will remain
usable from other processes that have been given it.
答案 1 :(得分:0)
您是否已将应用/设备组合注册到GCm项目?您必须首先在onRegistered方法中执行此操作。你添加了所有必要的权限吗? Google表示你不必在android 4.0上面添加自定义权限,但我的应用程序从来没有在没有用过的情况下工作。 如果您正在寻找一种更简单的GCM工作方式,我建议使用apiOmat:http://www.apiomat.com我知道它的后端即服务。但是,如果你的应用程序很小,你不需要支付任何费用,而且使用它会更容易。