如果您想通过您的活动(如果有任何正在运行)来处理传入的 Google Cloud 消息 (C2DM),或者如果没有任何活动正在运行,则下一个方法将很有效。
在清单文件中注册一个 BroadcastReceiver。每当应用程序未运行时,此接收器将处理 C2D 消息。在您的活动中以编程方式注册另一个 BroadcastReceiver。每当活动运行时,此接收器将处理 C2D 消息。
AndoroidManifest.xml
<receiver
android:name=".StaticReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.mypackage" />
</intent-filter>
</receiver>
MyReceiver.java
public class StaticReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Trigger a Notification
}
}
我的活动.java
public class MyActivity extends ActionBarActivity {
@Override
protected void onResume() {
super.onResume();
final IntentFilter filter = new
IntentFilter("com.google.android.c2dm.intent.RECEIVE");
filter.addCategory("com.mypackage");
filter.setPriority(1);
registerReceiver(dynamicReceiver, filter,
"com.google.android.c2dm.permission.SEND", null);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(dynamicReceiver);
}
private final BroadcastReceiver dynamicReceiver
= new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Handle C2DM
// blocks passing broadcast to StaticReceiver instance
abortBroadcast();
}
};
}
笔记!要首先捕获广播,dynamicReceiver IntentFilter 的优先级必须高于 StaticReceiver 实例 IntentFilter 的优先级(默认优先级为“0”)。
PS。看起来 Google Cloud Messaging Service 发出的广播是有序广播。原创意作者:CommonsWare