我遇到了同样的问题,谷歌似乎并不急于解决它。
我不想将已弃用的客户端帮助程序 gcm.jar 添加到我的应用程序中,因此我编写了一个适用于我的 Android 2.3.6 Nexus One 手机的最小解决方案,该手机注册失败,如上述问题
try {
gcm = GoogleCloudMessaging.getInstance(context);
regID = gcm.register(SENDER_ID);
storeRegistrationId(regID);
msg = "Device registered, registration ID=" + regID;
sendRegistrationIdToBackend();
} catch (IOException ex) {
msg = "Exception registering for GCM :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
oldSchoolRegister();
}
AUTHENTICATION_FAILED 触发了上面代码中的 IOException
private void oldSchoolRegister() {
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.setPackage("com.google.android.gsf");
setRegCallbackIntent(context, intent);
intent.putExtra("sender", SENDER_ID);
context.startService(intent);
}
private static synchronized void setRegCallbackIntent(Context context, Intent intent) {
regCallback = PendingIntent.getBroadcast(context, 0, new Intent(), 0);
intent.putExtra("app", regCallback);
}
public static synchronized void cancelRegCallbackIntent() {
if (regCallback != null) {
regCallback.cancel();
regCallback = null;
}
}
我将上面的代码添加到我的应用程序中。它们是 Client Helper gcm.jar 中的简化方法(因此您无需将 jar 添加到您的应用程序中)
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null && !extras.isEmpty()) { // has effect of unparcelling Bundle
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (messageType != null) {
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
showMessage(extras.getString("message")); // call your code
Logger.d(TAG, "Received message: " + message.alert + ": " + message.url);
} else if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
Logger.e(TAG, "Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
Logger.e(TAG, "Deleted messages on server: " + extras.toString());
}
} else {
String regID = extras.getString("registration_id");
if (regID != null && !regID.isEmpty()) {
doRegistration(regID); // send to your server etc.
GCMSetup.storeRegistrationId(regID);
GCMSetup.cancelRegCallbackIntent();
}
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
此代码位于意图服务中,并且有几行代码用于存储从 GCM 接收到的 ID。如您所见,与基本实现相比,只增加了大约 20 行代码,并且没有额外的依赖项!您只需要更新您的 AndroidManifest.xml 以确保您可以收到 REGISTRATION 意图。
<receiver android:name="com.camiolog.android.GCMBroadcastReceiver"
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.camiolog.android"/>
</intent-filter>
</receiver>
我希望这会有所帮助,直到谷歌齐心协力!