com.hukum.app_framework.application.gcm.controller.AppGcmRegistrationIntentService.java Source code

Java tutorial

Introduction

Here is the source code for com.hukum.app_framework.application.gcm.controller.AppGcmRegistrationIntentService.java

Source

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

package com.hukum.app_framework.application.gcm.controller;

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.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.hukum.app_framework.application.model.listener.OnAPIResponseListener;
import com.hukum.app_framework.application.gcm.model.manager.GcmManager;
import com.hukum.app_framework.application.gcm.model.parser.GcmParser;
import com.hukum.app_framework.application.model.data.AppData;
import com.hukum.app_framework.application.constants.RequestTagConstant;
import com.hukum.app_framework.application.constants.SharedPreferenceConstant;

import org.json.JSONException;

import java.io.IOException;

public class AppGcmRegistrationIntentService extends IntentService implements OnAPIResponseListener {

    private static final String TAG = "AppGcmRegistration";
    private static final String[] TOPICS = { "global" };

    public static final String SENDER_ID = "32670831119";

    public AppGcmRegistrationIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            // [START register_for_gcm]
            // 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(SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            // [END get_token]
            Log.i(TAG, "GCM Reg Token: " + token);
            sendRegistrationToServer(token);
            // Subscribe to topic channels
            subscribeTopics(token);
            // [END register_for_gcm]
        } catch (Exception e) {
            Log.d(TAG, "NcertGcmRegService onHandleIntent" + e);
            handleTokenFailure();
        }
    }

    /**
     * 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) {
        Log.d(TAG, "GcmRegService token" + token);
        GcmManager gcmManager = new GcmManager(new GcmParser(), this);
        gcmManager.sendGcmTokenToServer(RequestTagConstant.SEND_GCM_ACCESS_TOKEN, token, this);

    }

    /**
     * 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) throws IOException {
        GcmPubSub pubSub = GcmPubSub.getInstance(this);
        for (String topic : TOPICS) {
            pubSub.subscribe(token, "/topics/" + topic, null);
        }
    }

    // [END subscribe_topics]
    /**
     * When we get HTTP 200 as response Code.
     *
     * @param appData
     * @param requestTag
     */
    @Override
    public void onAPIResponse(AppData appData, String requestTag) {

        Log.d(TAG, "NcertGcmRegService onAPIResponse" + appData);

        if (appData != null && appData.isSucceeded()) {
            if (requestTag.equals(RequestTagConstant.SEND_GCM_ACCESS_TOKEN)) {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                // 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(SharedPreferenceConstant.SENT_TOKEN_TO_SERVER, true).apply();
                // Notify UI that registration has completed, so the progress indicator can be hidden.
                Intent registrationComplete = new Intent(SharedPreferenceConstant.REGISTRATION_COMPLETE);
                LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
            }
        } else {
            handleTokenFailure();
        }
    }

    private void handleTokenFailure() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        Log.d(TAG, "Failed to complete token refresh");
        // 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(SharedPreferenceConstant.SENT_TOKEN_TO_SERVER, false).apply();
        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(SharedPreferenceConstant.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    /**
     * When we get other then HTTP 200 as response Code.
     *
     * @param message
     * @param requestTag
     */
    @Override
    public void onInternalServerError(String message, String requestTag) {
        Log.d(TAG, "NcertGcmRegService onInternalServerError" + message);
        handleTokenFailure();
    }

    /**
     * When api get broken or response structure changes.
     *
     * @param e
     * @param requestTag
     */
    @Override
    public void onAPIParsingException(JSONException e, String requestTag) {
        Log.d(TAG, "NcertGcmRegService onAPIParsingException" + e);
        handleTokenFailure();
    }
}