我可以使用 <receiver>
向 C2DM 成功注册我的 android 应用程序在我的 list 中。但是,如果我删除 <receiver>
从 list 中使用上下文的方法 registerReceiver 注册我的接收器,我收到一个 SERVICE_NOT_AVAILABLE
错误响应。我已经在模拟器和真实设备中重现了这种行为。
是否可以动态注册 C2DM 接收器?
这是我删除的 list fragment :
<receiver android:name=".service.C2DM.C2DMReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="mytestapp" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="mytestapp" />
</intent-filter>
</receiver>
代码如下:
public class C2DMReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) {
//TODO: Registration failed, should try again later.
Log.e("MyTestAppC2DM", "C2DM Error = " + intent.getStringExtra("error"));
} else if (intent.getStringExtra("unregistered") != null) {
Log.d("MyTestAppC2DM", "C2DM Unregistered");
} else if (registration != null) {
Log.d("MyTestAppC2DM","C2DM registration_id = " + registration);
} else {
Log.w("MyTestAppC2DM", "C2DM No registration_id");
}
}
public static void register(Context context){
/* BEGIN OF DYNAMIC REGISTER */
C2DMReceiver c2dmReceiver = new C2DMReceiver();
IntentFilter receiveIntentFilter = new IntentFilter();
receiveIntentFilter.addAction("com.google.android.c2dm.intent.RECEIVE");
receiveIntentFilter.addCategory("mytestapp");
context.registerReceiver(c2dmReceiver, receiveIntentFilter, "com.google.android.c2dm.permission.SEND", null);
IntentFilter registrationIntentFilter = new IntentFilter();
registrationIntentFilter.addAction("com.google.android.c2dm.intent.REGISTRATION");
registrationIntentFilter.addCategory("mytestapp");
context.registerReceiver(c2dmReceiver, registrationIntentFilter, "com.google.android.c2dm.permission.SEND", null);
/*END OF DYNAMIC REGISTER*/
Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));
registrationIntent.putExtra("sender", "mysender@gmail.com");
ComponentName service = context.startService(registrationIntent);
if(service!=null){
Log.d("MyTestAppC2DM","C2DM Registration sent");
}else{
Log.d("MyTestAppC2DM","C2DM Service not found");
}
}
}
最佳答案
您可以在 list 文件中注册接收器 C2DMReceiver,并将 Intent 分派(dispatch)给真正的 BroadcastReceiver 来处理它。
关于android - 使用registerReceiver动态注册C2DM接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10322516/