0

我指的是标准的 Android GCM 教程

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

我在 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 中调用的。

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

4

2 回答 2

0

使用带有字符串参数的抽象方法创建一个说“GCMInterface”的接口,让您的活动实现此接口,即您想对 regId 做什么。将您的活动引用传递给您的 GCMIntentService。当调用 GCMIntentservice 的 onREgistered 方法时,调用 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);
        }

    }

}

我希望你明白我的意思。

于 2012-10-23T08:21:00.497 回答
0

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

于 2012-10-23T07:31:58.597 回答