Java tutorial
package com.contactlab.clabpush_android_sample; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.contactlab.clabpush_android.Manager; import com.contactlab.clabpush_android.connections.ConnectionTask; import com.contactlab.clabpush_android.connections.Response; 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; import java.net.HttpURLConnection; /* * Copyright 2012-2015 ContactLab, Italy * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ public class RegistrationIntentService extends IntentService implements ConnectionTask.ConnectionTaskListener { /** * Action bundled as an Intent's extra. */ public static final String EXTRA_ACTION = "Action"; /** * Default value for the action, do nothing. */ public static final int ACTION_UNKNOWN = 0; /** * Perform registration. */ public static final int ACTION_REGISTER = 1; /** * Perform unregistration. */ public static final int ACTION_UNREGISTER = 2; /** * Request code for the registration request. */ public static final int REQUEST_REGISTRATION = 1; /** * Request code for the unregistration request. */ public static final int REQUEST_UNREGISTRATION = 2; private static String TAG = "RegistrationIntentService"; private static final String[] TOPICS = { "global" }; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { int action = intent.getIntExtra(EXTRA_ACTION, ACTION_UNKNOWN); if (action == ACTION_REGISTER) { register(); } else if (action == ACTION_UNREGISTER) { unregister(); } } /** * This method will first attemp to retrive a device token with {@link InstanceID#getToken(String, String, Bundle)}, subscribe to the {@link #TOPICS}, * prepare a {@link Data} object and attemp to register the token and the data on the CLabPush-Go server via {@link Manager#registerDevice(Context, int, String, Object, ConnectionTask.ConnectionTaskListener)}. * A successfull registration will be handled in {@link #onTaskResult(ConnectionTask, int, Response)}, while any Exception thrown in the process will treated as failure. */ private void register() { try { synchronized (TAG) { String senderID = getString(R.string.gcm_senderId); if (BuildConfig.DEBUG && senderID.length() == 0) { throw new AssertionError( "gcm_senderId string resource is not set. If you don't have a GCM Sender ID, refer to the GCM documentation to obtain one."); } // Get the token. InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // Get the GCM token // Subscribe to topics. subscribeTopics(token, TOPICS); // Save the token and clear the previous registration status. SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.edit().putBoolean(MainActivity.PREF_TOKENSENT, false) .putString(MainActivity.PREF_TOKEN, token).apply(); // Attemp registration on the server. Data data = Data.newInstance(this); Manager.MANAGER.registerDevice(this, REQUEST_REGISTRATION, token, data, this); } } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh"); e.printStackTrace(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.edit().putBoolean(MainActivity.PREF_TOKENSENT, false).remove(MainActivity.PREF_TOKEN) .apply(); } finally { Intent registrationCompleted = new Intent(MainActivity.MSG_REGISTRATION_COMPLETED); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationCompleted); } } /** * This method will retrive the device token stored in the SharedPreferences and, if set, will * use {@link Manager#unregisterDevice(Context, int, String, ConnectionTask.ConnectionTaskListener)} to * perform the unregistration on the CLabPush-Go server. */ private void unregister() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String token = preferences.getString(MainActivity.PREF_TOKEN, null); if (token != null) { Manager.MANAGER.unregisterDevice(this, REQUEST_UNREGISTRATION, token, this); } } /** * Subscribe to GCM topics. * @param token The device token. * @param topics A list of topics you want to subscribe to. * @throws IOException If something goes wrong with the subscription. */ private void subscribeTopics(String token, String[] topics) throws IOException { for (String topic : TOPICS) { GcmPubSub pubSub = GcmPubSub.getInstance(this); pubSub.subscribe(token, "/topics/" + topic, null); } } //region ConnectionTaskListener @Override public void onTaskResult(ConnectionTask task, int requestCode, Response response) { if (requestCode == REQUEST_REGISTRATION) { if (response.responseCode == HttpURLConnection.HTTP_CREATED) { // The server returned 201 - Created as response code, we can flag the PREF_TOKENSENT flag in the SharedPreferences as true. SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.edit().putBoolean(MainActivity.PREF_TOKENSENT, true).apply(); Intent registrationCompleted = new Intent(MainActivity.MSG_REGISTRATION_COMPLETED); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationCompleted); } } else if (requestCode == REQUEST_UNREGISTRATION) { if (response.responseCode == HttpURLConnection.HTTP_OK) { // The server returned 200 - OK, we can set the PREF_TOKENSENT flag as false. SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.edit().putBoolean(MainActivity.PREF_TOKENSENT, false).apply(); Intent registrationCompleted = new Intent(MainActivity.MSG_REGISTRATION_COMPLETED); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationCompleted); } } } //endregion }