GCMRegistrar.getRegistrationId在首次启动App时返回空String

时间:2012-10-23 07:23:42

标签: android google-cloud-messaging

我指的是standard Android GCM Tutorial

似乎在第一次应用启动时,在oncreate()方法触发后设置了注册ID。如何将注册ID从GCMRegistrar.java发送回活动?

我在MainActivity的onCreate()中调用它:

GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    String regId = GCMRegistrar.getRegistrationId(this);

    //provide RegID for the Class that can communicate with Javascript.


    Log.v(TAG, "regID: "+regId);
    if (regId.equals("")) {
      GCMRegistrar.register(this, SENDER_ID);

    } else {
      Log.v(TAG, "Already registered");

    }

    EDIT:
    //Call after .register also returns empty String on first App Launch
    String regId2 = GCMRegistrar.getRegistrationId(this);// returns ""

首次启动时返回一个空字符串。在日志中,我看到注册ID稍后在GCMRegistrar.java中设置

static String setRegistrationId(Context context, String regId) {
    Log.v(TAG, "REGISTRATION ID IN SET: "+regId);
    final SharedPreferences prefs = getGCMPreferences(context);
    String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
    int appVersion = getAppVersion(context);
    Log.v(TAG, "Saving regId on app version " + appVersion);
    Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID, regId);
    editor.putInt(PROPERTY_APP_VERSION, appVersion);
    editor.commit();
    return oldRegistrationId;
}

上面的方法在GCMBaseIntentService中调用。

如果我第二次运行应用程序,我可以获得Reg。在Mainactivity中的ID,我如何实现类似回调函数的东西,以便我可以访问Reg。 MainActivity中的ID?

2 个答案:

答案 0 :(得分:0)

如果您未在GCM注册,GCMRegistrar.getRegistrationId(this)将返回空字符串。一旦您注册,它将返回实际的注册ID。因此,他们在演示中使用if()条件来检查此设备是否已注册

答案 1 :(得分:0)

使用带有字符串参数的抽象方法创建一个接口说“GCMInterface”,让你的活动实现这个接口,即你想用regId做什么。将活动的引用传递给GCMIntentService。当调用onGgistered方法的GCMIntentservice时,调用activity.method并将regId作为参数传递。

public interface GCMInterface {
    public void mOnRegistered(String id);
}

...

public class MyActivity implements GCMInterface {

    // implementation of GCMInterface interaface
    public void mOnRegistered(String id) {
        // do whatever you want to do with id
    }
}
...
public class GCMIntentService extends GCMBaseIntentService {


    GCMInterface interface;   // initialize it with your activity's context
    public GCMIntentService() {
    }

    @Override
    protected void onRegistered(Context context, String regId) {
        // call mOnRegistered method with your activity's context like
        interface = (GCMInterface)context;
        if(interface != null) {
            interface.mOnRegistered(regId);
        }

    }

}

我希望你明白我的观点。