从intent获取额外内容的问题:

时间:2015-09-24 09:19:28

标签: java android

我有以下广播接收器:

 mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                System.out.println("onReceive");
                final String token1 = intent.getStringExtra("token");
                System.out.println("onReceive" + token1);
                Bundle extras = getIntent().getExtras();
                if (extras != null) {
                    final String token = intent.getStringExtra("token");
                    System.out.println("Token fetched");
                    new PostLoginWithGCM(cleanKey, token).execute();
                } else {
                    System.out.println("Token null");
                }
            }
        };

输出结果为:

09-24 14:44:04.741 9103-9103/com.exa.exaCRM I/System.out: onReceive
09-24 14:44:04.741 9103-9103/com.exa.exaCRM I/System.out: onReceivefy6gmbUODWk:APA91bHf3PrCQmzZXnfR5LU40C7Mu1jhHenX8SvYR2OvQR6A3npXKa4NF8J-eZtHoxO7QAbTe_S94L8IttuU7ZrT5S97mucJb6EmmF92y3Hi60lrGb6cBfjDHj9fYDfaL8chion-Uyh5
09-24 14:44:04.741 9103-9103/com.exa.exaCRM I/System.out: Token null

所以第一个System.out onReceive工作正常。

第二个System.out给出了我用Intent传递的标记值。

最后,我检查我的额外内容是否为空,令我惊讶的是它说我的附加内容为空,而我只是在空检查之前打印了数据。

这是负责为我生成令牌和本地广播的方法:

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);


    try {

        InstanceID instanceID = InstanceID.getInstance(this);
        token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

        Log.i(TAG, "GCM Registration Token: " + token);

        subscribeTopics(token);
        sharedPreferences.edit().putBoolean(SessionManager.SENT_TOKEN_TO_SERVER, true).apply();
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        sharedPreferences.edit().putBoolean(SessionManager.SENT_TOKEN_TO_SERVER, false).apply();
    }

    Intent registrationComplete = new Intent(SessionManager.REGISTRATION_COMPLETE);
    System.out.println("token before assignment" + token);
    registrationComplete.putExtra("token", token.toString());
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

1 个答案:

答案 0 :(得分:2)

在onReceive方法中,您已将intent作为参数。 所以不是这个

   Bundle extras = getIntent().getExtras();

试试这个

    Bundle extras = intent.getExtras();