我继承了一个已经实现了GCM服务并且运行良好的应用程序。
我说的很好,因为有一半时间,当应用程序启动时,我收到错误INVALID_SENDER
而另一半我得不到它!
我得到错误的次数和我没有得到的次数没有区别(或者我可能错过了差异)。
我会不时从GCM收到消息(登录后我没有收到INVALID_SENDER
)
这是我主要活动的onCreate()
中的注册码
private void registerGCM() throws Exception {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
CommonUtilities.DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
ServerUtilities.register(mContext, regId);
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(context, regId);
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
我的清单文件
<receiver
android:name="com.mixpanel.android.mpmetrics.GCMReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.says.broadcaster" />
</intent-filter>
</receiver>
<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.says.broadcaster" />
</intent-filter>
</receiver>
我有两个接收器的原因是我从我正在使用的统计跟踪API获得推送通知,并且他们使用GCM。
我的应用程序每周左右都有一个新版本,我正在阅读我需要在应用更新后注册一个新ID。这可能是问题吗?
相关问题: Getting INVALID_SENDER on one device while its working with another GCM android
答案 0 :(得分:7)
GCM发送的广播似乎是订购的。这意味着它们一次只能交付一个。库的接收器有时可能会在接收器之前被调用,并且可能会阻止您的接收器被调用(如果它取消了广播)。
有几种方法可以处理它。一种方法是给你的接收器一个比图书馆接收器更高的优先级。只需将android:priority
属性添加到两个接收器的intent-filter
,并为您的接收器提供更高的优先级。
有序广播(与Context.sendOrderedBroadcast一起发送)一次传送到一个接收器。当每个接收器依次执行时,它可以将结果传播到下一个接收器,或者它可以完全中止广播,以便它不会传递给其他接收器。可以使用匹配的intent-filter的android:priority属性来控制运行的订单接收器;具有相同优先级的接收器将以任意顺序运行。
当您的广播接收器被呼叫时,您应该检查intent.getExtras ().get("from")
是否包含您正在使用的发送者ID。只有在这种情况下你应该处理广播。如果它是不同的发件人ID,则可能是库使用的发件人ID,您应该让库处理它。
如果这不能解决问题,您可以考虑在清单中仅声明接收方,并在必要时将GCM广播转发给其他接收方。