【问题标题】:Passing token Google Cloud Messaging between activities在活动之间传递令牌谷歌云消息传递
【发布时间】:2016-05-22 08:58:15
【问题描述】:

我想将令牌从一个活动传递到另一个活动,但我不知道我能做什么,因为使用 Intent 有问题。

通过这个活动我得到了令牌:

public class RegistrationIntentService extends IntentService {

// abbreviated tag name
static final String TAG = "RegIntentService";

public RegistrationIntentService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {
    // Make a call to Instance API
    InstanceID instanceID = InstanceID.getInstance(this);
    String senderId = getResources().getString(R.string.gcm_defaultSenderId);
    try {
        // request token that will be used by the server to send push notifications
        String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
        Log.d(TAG, "GCM Registration Token: " + token);
        // pass along this data
        sendRegistrationToServer(token);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    }
}

通过这个活动,我将代码传递到我的服务器中:

  public void userLogin(View view){
    login_name = ET_NAME.getText().toString();
    login_pass = ET_PASS.getText().toString();
    String method = "login";
    String token = getRegTokenId();
    BackgroundTaskLogin backgroundTask = new BackgroundTaskLogin(mContext);
    backgroundTask.execute(method, login_name, login_pass, token);
}



private void getRegTokenId(){
    Intent intent = new Intent(mContext, RegistrationIntentService.class);
    startService(intent);
}

提前致谢。

【问题讨论】:

    标签: java android android-intent google-cloud-messaging token


    【解决方案1】:

    您似乎有些困惑。您的RegistrationIntentService 实际上是服务而不是活动,下面的代码可能包含在活动中。

    很难准确说出您要做什么,但我猜userLogin() 方法应该使用您活动中的一些信息来生成 GCM 设备令牌,然后将您的用户登录到某个服务器并将 GCM 设备令牌作为登录期间发送的信息的一部分。

    您假设getRegTokenId() 将返回 GCM 设备令牌,但它不会,实际上它返回 void,如您的代码中所定义。

    private void getRegTokenId(){
        Intent intent = new Intent(mContext, RegistrationIntentService.class);
        startService(intent);
    }
    

    看起来您正在尝试遵循教程或其他内容,在这种情况下,似乎想法是 RegistrationIntentService 应该处理登录服务的部分,或者至少上传令牌。

    public void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
        }
    }
    

    所以我认为您真正想要做的不是在活动中获取令牌,我认为您希望将其余登录信息获取到服务中,以便sendRegistrationToServer() 可以使用它

    您可以将该信息添加到您发送给startService()的意图中

    private void getRegTokenId(){
        Intent intent = new Intent(mContext, RegistrationIntentService.class);
        intent.putExtra("SOME_KEY","SOME_VALUE"); // add info to the intent
        startService(intent);
    }
    

    然后,您可以使用

    将其恢复到服务中
    someValue = getStringExtra("SOME_KEY");
    

    如果你真的想从服务中取回令牌,也有办法做到这一点,你可以阅读意图服务here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      相关资源
      最近更新 更多