为 GCM 推送通知获取注册 ID 的正确设计模式?
Proper design pattern to grab registration id for GCM push notifications?
我有一个 activity 调用了一个名为 LoadAuthenticateEvent
的 Otto Event
这个事件然后转到我的 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
可能为空。
如果您想在 UI 线程上调用 sClient(不确定这是否适合您),请在 GCM 返回您的 GCM 注册 ID 后使用处理程序调用它。
接受的答案 here 有示例代码可以帮助您。
我最终使用 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
class
中非常有效
联系 GCM 的最佳方式是通过 services。
创建一个 IntentService 来捕获从
activity
onHandleIntent(Intent intent)
设备发送服务请求 GCM 并接收 tokenID。
InstanceID instanceID = InstanceID.getInstance(this);
字符串标记 = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, 空);
实施此方法以将任何注册发送到您应用程序的服务器。
sendRegistrationToserver(token)
通知UI注册完成
意图注册完成=新意图(GcmUtils.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(注册完成);
- (可选)订阅主题频道
private void subscribeTopics(String token, ArrayList topics_gcm)throws IOException {
对于(字符串主题:topics_gcm){
GcmPubSub pubSub = GcmPubSub.getInstance(this);
pubSub.subscribe(令牌,主题,空);
}
}
完整的 IntentService:
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]
}
- 从任何上下文启动 IntentService:activity,服务....
Intent intent = new Intent(getContext(), egistrationIntentService.class);
intent.putCharSequenceArrayListExtra("topics_gcm", topcics_gcm);
getContext().startService(intent);
我有一个 activity 调用了一个名为 LoadAuthenticateEvent
的 Otto Event
这个事件然后转到我的 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
可能为空。
如果您想在 UI 线程上调用 sClient(不确定这是否适合您),请在 GCM 返回您的 GCM 注册 ID 后使用处理程序调用它。
接受的答案 here 有示例代码可以帮助您。
我最终使用 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
class
联系 GCM 的最佳方式是通过 services。
创建一个 IntentService 来捕获从 activity
onHandleIntent(Intent intent)
设备发送服务请求 GCM 并接收 tokenID。
InstanceID instanceID = InstanceID.getInstance(this); 字符串标记 = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, 空);
实施此方法以将任何注册发送到您应用程序的服务器。
sendRegistrationToserver(token)
通知UI注册完成
意图注册完成=新意图(GcmUtils.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(注册完成);
- (可选)订阅主题频道 private void subscribeTopics(String token, ArrayList topics_gcm)throws IOException { 对于(字符串主题:topics_gcm){ GcmPubSub pubSub = GcmPubSub.getInstance(this); pubSub.subscribe(令牌,主题,空); } }
完整的 IntentService:
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]
}
- 从任何上下文启动 IntentService:activity,服务....
Intent intent = new Intent(getContext(), egistrationIntentService.class); intent.putCharSequenceArrayListExtra("topics_gcm", topcics_gcm); getContext().startService(intent);