0

我有一个Otto Event调用LoadAuthenticateEvent此事件的活动,然后转到我ClientManager.java的以下代码所在的位置:

@Subscribe
public void onLoadAuthenticateEvent(LoadAuthenticateEvent loadAuthenticateEvent) {

    // GCM cannot register on the main thread
    String deviceID = "";
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String differentId = GCMRegistrationUtil.registerDevice(mContext);
            Log.d(TAG, "Device Id: " + differentId);
        }
    });
    thread.start();


    String email = loadAuthenticateEvent.getEmail();
    String password = loadAuthenticateEvent.getPassword();

    Callback<User> callback = new Callback<User>() {
        @Override
        public void success(User user, Response response) {
            sClient.setOrganization(user.getRole().getOrganization().getSubdomain());
            mBus.post(new LoadedMeEvent(user));
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            mBus.post(new LoadedErrorEvent(retrofitError));
        }
    };

    sClient.authenticate(email, password, deviceID, PLATFORM, callback);
}

问题是服务器需要deviceID,但GCM要求调用是异步的,而不是在主线程上,我应该如何去实现这个我可以正确获取 deviceID 然后将它传递给sClient?因为它deviceID可能是空的。

4

3 回答 3

2

联系GCM的最佳方式是通过服务

  1. 创建一个IntentService来捕获从 Activity 释放的意图

    onHandleIntent(意图意图)

  2. 设备发送服务请求 GCM 并接收 tokenID。

    InstanceID instanceID = InstanceID.getInstance(this); 字符串令牌 = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

  3. 实施此方法以将任何注册发送到您的应用程序的服务器。

    发送注册到服务器(令牌)

  4. 通知 UI 注册完成

    Intent registrationComplete = new Intent(GcmUtils.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);

  5. (可选)订阅主题频道 private void subscribeTopics(String token, ArrayList topics_gcm)throws IOException { for (String topic : topics_gcm) { GcmPubSub pubSub = GcmPubSub.getInstance(this); pubSub.subscribe(token, topic, null); } }

全意向服务:

public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";

public RegistrationIntentService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {

    ArrayList<String> topics_gcm = intent.getStringArrayListExtra("topics_gcm");
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {
        // In the (unlikely) event that multiple refresh operations occur simultaneously,
        // ensure that they are processed sequentially.
        synchronized (TAG) {
            // Initially this call goes out to the network to retrieve the token, subsequent calls
            // are local.
            // [START get_token]
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            // [END get_token]
            Log.i(TAG, "GCM Registration Token: " + token);

            // TODO: Implement this method to send any registration to your app's servers.
            //sendRegistrationToServer(token);

            // TODO: Subscribe to topic channels
            //subscribeTopics(token, topics_gcm);

            // You should store a boolean that indicates whether the generated token has been
            // sent to your server. If the boolean is false, send the token to your server,
            // otherwise your server should have already received the token.
            sharedPreferences.edit().putBoolean(GcmUtils.SENT_TOKEN_TO_SERVER, true).apply();
            // [END register_for_gcm]
        }
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        sharedPreferences.edit().putBoolean(GcmUtils.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(GcmUtils.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

/**
 * Persist registration to third-party servers.
 *
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
}

/**
 * Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
 *
 * @param token GCM token
 * @throws IOException if unable to reach the GCM PubSub service
 */
// [START subscribe_topics]
private void subscribeTopics(String token, ArrayList<String> topics_gcm) throws IOException {
    for (String topic : topics_gcm) {
        GcmPubSub pubSub = GcmPubSub.getInstance(this);
        pubSub.subscribe(token, topic, null);
    }
}
// [END subscribe_topics]

}

  1. 从任何上下文启动 IntentService:活动、服务....
    Intent intent = new Intent(getContext(), egistrationIntentService.class); intent.putCharSequenceArrayListExtra("topics_gcm", topcics_gcm); getContext().startService(intent);
于 2015-08-28T19:48:27.657 回答
0

如果您想在 UI 线程上调用 sClient(不确定这是否适合您),请在 GCM 返回 GCM 注册 ID 后使用 Handler 调用它。

这里接受的答案有示例代码来帮助你。

于 2015-04-03T18:31:59.617 回答
0

我最终AsyncTask为这个特定的东西使用了一个,如下所示:

private void registerInBackground() {

    new AsyncTask<Void, Void, String>() {

        @Override
        protected String doInBackground(Void... params) {
            String regId = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(mContext);
                }

                regId = gcm.register(GCMConfig.getSenderId());
                storeRegistrationId(mContext, regId);

            } catch (IOException e) {
                Log.e(TAG, "Error: ", e);
                e.printStackTrace();
            }

            Log.d(TAG, "GCM AsyncTask completed");
            return regId;
        }

        @Override
        protected void onPostExecute(String result) {

            // Get the message
            Log.d(TAG, "Registered with GCM Result: " + result);

        }

    }.execute(null, null, null);

}

这在GCMRegistration课堂上非常有效

于 2015-05-31T04:53:49.263 回答