我终于让应用程序可以使用 GCM(Google Cloud Messaging)了。但我有一个问题。注册完成后的那一刻,我想获取registrationId。除了registrationId为空,除非我重新启动应用程序,否则它会返回一个值。
基本上我想要的是在注册完成后立即检索 registerId 。
这是我正在使用的代码:
checkNotNull(SENDER_ID, "SENDER_ID");
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
TextView mDisplay = (TextView) findViewById(R.id.display);
String regId = "";
if (!GCMRegistrar.isRegistered(this))
{
mDisplay.setText("registering");
GCMRegistrar.register(this, SENDER_ID);
regId = GCMRegistrar.getRegistrationId(this);
String url = "localhost/Google-Cloud-Messaging-Server-Test/registration.php?regId=" + regId;
Log.i(TAG, "registration url: " + url);
HttpRequest httprequest = new HttpRequest(url);
}
else
{
regId = GCMRegistrar.getRegistrationId(this);
mDisplay.setText(regId);
Log.v(TAG, "Already registered");
GCMRegistrar.unregister(this);
}
问题是代码到了这一步之后:
regId = GCMRegistrar.getRegistrationId(this);
String url = "localhost/Google-Cloud-Messaging-Server-Test/registration.php?regId=" + regId;
regId 为空。它应该有一个值,因为注册成功。难道我做错了什么?是否有可能在它实际上仍在经历注册过程时尝试获取registrationId?
在此先感谢,
马克
编辑: manifest.xml 内容
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codeglue.google.cloud.messaging.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<permission
android:name="com.codeglue.google.cloud.messaging.test.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.codeglue.google.cloud.messaging.test.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gcm.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.codeglue.google.cloud.messaging.test" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>