Về cơ bản, bạn nên làm như sau trong hoạt động chính của bạn:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, GCMIntentService.GCM_SENDER_ID);
} else {
Log.v(TAG, "Already registered");
}
}
Sau đó bạn nên gửi id đăng ký đến máy chủ ứng dụng của bạn, bất cứ khi nào ứng dụng nhận được một com.google.android.c2dm.intent.REGISTRATION
ý định với một registration_id
thêm. Điều này có thể xảy ra khi Google định kỳ cập nhật id của ứng dụng.
Bạn có thể đạt được điều này bằng cách mở rộng com.google.android.gcm.GCMBaseIntentService
với thực hiện của riêng bạn, ví dụ .:
public class GCMIntentService extends GCMBaseIntentService {
// Also known as the "project id".
public static final String GCM_SENDER_ID = "XXXXXXXXXXXXX";
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(GCM_SENDER_ID);
}
@Override
protected void onRegistered(Context context, String regId) {
// Send the regId to your server.
}
@Override
protected void onUnregistered(Context context, String regId) {
// Unregister the regId at your server.
}
@Override
protected void onMessage(Context context, Intent msg) {
// Handle the message.
}
@Override
protected void onError(Context context, String errorId) {
// Handle the error.
}
}
Để biết thêm chi tiết, tôi sẽ (lại) đọc tài liệu cho writing the client side code và the Advanced Section of the GCM documentation.
Hy vọng điều đó sẽ hữu ích!
có thể trùng lặp với [Thay đổi ID đăng ký xử lý trong Google Cloud Messaging trên Android] (http://stackoverflow.com/questions/16838654/handling-registration-id-changes-in-google-cloud-messaging-on -android) – Eran