Java tutorial
/** * Copyright 2015 Google Inc. All Rights Reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.crazymike.service; import android.app.IntentService; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.crazymike.R; import com.crazymike.respositories.AppApi2Repository; import com.crazymike.util.PreferencesKey; import com.crazymike.util.PreferencesTool; import com.crazymike.util.QuickstartPreferences; import com.google.android.gms.gcm.GcmPubSub; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import java.io.IOException; public class RegistrationIntentService extends IntentService { private static final String TAG = RegistrationIntentService.class.getSimpleName(); private static final String[] TOPICS = { "global" }; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); try { InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); PreferencesTool.getInstance().put(PreferencesKey.GCM_TOKE, token); Log.i(TAG, "GCM Registration Token: " + token); sendRegistrationToServer(token); subscribeTopics(token); sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply(); } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply(); } Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } private void sendRegistrationToServer(String token) { AppApi2Repository.getInstance().addDeviceToken(token).subscribe(o -> { }, Throwable::printStackTrace); } private void subscribeTopics(String token) throws IOException { GcmPubSub pubSub = GcmPubSub.getInstance(this); for (String topic : TOPICS) { pubSub.subscribe(token, "/topics/" + topic, null); } } }