它不是那样工作的。
GCMRegistrar.register
向 GCM 服务器发起请求,要求其提供注册 ID。这是一个异步请求。GCMRegistrar.getRegistrationId
返回注册 ID 的缓存值,因此如果您的设备未注册,则返回 null。
注册 ID 返回在GCMIntentService.onRegistered
method.
这是代码GCM意图服务来自 GCM 演示。
这是代码GCMRegistrar.getRegistrationId
:
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* @return registration id, or empty string if the registration is not
* complete.
*/
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
Log.v(TAG, "App version changed from " + oldVersion + " to " +
newVersion + "; resetting registration id");
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
正如您所看到的,它返回本地存储的注册 ID 值。为了让它返回任何东西,GCMRegistrar.setRegistrationId(Context context, String regId)
必须使用返回的注册 ID 进行调用GCMIntentService
。
它被称为GCMBaseIntentService
:
private void handleRegistration(final Context context, Intent intent) {
GCMRegistrar.cancelAppPendingIntent();
String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
String error = intent.getStringExtra(EXTRA_ERROR);
String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
Log.d(TAG, "handleRegistration: registrationId = " + registrationId +
", error = " + error + ", unregistered = " + unregistered);
// registration succeeded
if (registrationId != null) {
GCMRegistrar.resetBackoff(context);
GCMRegistrar.setRegistrationId(context, registrationId);
onRegistered(context, registrationId);
return;
}
...
}