我目前正在将GCM应用到我的应用中。我使用教程here作为起点。
问题是我的regId
始终是null
:
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals(""))
{
GCMRegistrar.register(this, "627xxxx78");
}
else
{
if (GCMRegistrar.isRegisteredOnServer(this))
{
Log.i(TAG, "Already registered regId : " + regId );
}
else
{
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;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
在上面的代码中,ServerUtilities.register
永远不会被调用,因为GCMRegistrar.getRegistrationId(this)
;总是返回一个空字符串。
有什么想法吗?
答案 0 :(得分:2)
我遇到了同样的问题。在应用程序清单文件中添加以下内容:
package="yourApplicationPackage"
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<permission
android:name="yourApplicationPackage.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission
android:name="yourApplicationPackage.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission
android:name="com.google.android.c2dm.permission.RECEIVE" />
<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="yourApplicationPackage" />
</intent-filter>
</receiver>
<service android:name="yourApplicationPackage.GCMIntentService"/>
必须在应用程序包
中保留此“yourApplicationPackage.GCMIntentService”yourApplicationPackage.GCMIntentService代码是这样的。
public class GCMIntentService extends GCMBaseIntentService {
@Override
protected void onError(Context arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
protected void onMessage(Context context, Intent intent) {
// TODO Auto-generated method stub
}
@Override
protected void onRegistered(Context context, String registrationId) {
// TODO Auto-generated method stub
Log.i(TAG, "Device registered: regId = " + registrationId);
GcmServer.register(context, registrationId);
}
@Override
protected void onUnregistered(Context arg0, String arg1) {
// TODO Auto-generated method stub
}
答案 1 :(得分:2)
确保您的模拟器或设备已使用Google帐户登录。我遇到了同样的问题。我只是登录了设备的谷歌帐户,并且lolz,我得到了regId。