trogdor.itemhunter.mobileapp.GcmIntentService.java Source code

Java tutorial

Introduction

Here is the source code for trogdor.itemhunter.mobileapp.GcmIntentService.java

Source

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * 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 trogdor.itemhunter.mobileapp;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;

import java.util.ArrayList;

/**
 * This {@code IntentService} does the actual handling of the GCM message.
 * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
 * partial wake lock for this service while the service does its work. When the
 * service is finished, it calls {@code completeWakefulIntent()} to release the
 * wake lock.
 *
 * Adapted from GCM demo at https://developer.android.com/google/gcm/client.html
 */
public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;

    private static final String KEY_NOTIF_TYPE = "notificationType";
    private static final String KEY_BID_AMOUNT = "amount";
    private static final String KEY_ITEM_ID = "itemId";
    private static final String KEY_CUSTOM_MSG = "message";

    public static final String TYPE_OUTBID = "outbid";
    public static final String TYPE_CUSTOM = "custom";

    public GcmIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        String messageType = GoogleCloudMessaging.getInstance(this).getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                if (extras.getString(KEY_NOTIF_TYPE).equals(TYPE_OUTBID)) {
                    sendOutbidNotification(extras);
                } else if (extras.getString(KEY_NOTIF_TYPE).equals(TYPE_CUSTOM)) {
                    displayNotification(extras.getString(KEY_CUSTOM_MSG), null);
                }
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                displayNotification("Send error: " + extras.toString(), null);
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                displayNotification("Deleted messages on server: " + extras.toString(), null);
            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendOutbidNotification(Bundle payload) {
        PendingIntent onClick;
        OutbidNotification notification;
        ArrayList<Item> items = new ServerHandler(getApplicationContext()).getDateCompliantGson()
                .fromJson(PreferenceManager.getDefaultSharedPreferences(this).getString(Auction.STORAGE_KEY, ""),
                        Auction.class)
                .getItems();

        // Find the item the user was outbid on
        for (Item item : items) {
            if (item.getId().equals(payload.getString(KEY_ITEM_ID))) {
                if (Session.isLoggedIn()) {
                    onClick = PendingIntent
                            .getActivity(this, 0,
                                    new Intent(this, ItemDetailsActivity.class)
                                            .putExtra(ItemDetailsActivity.ITEM_TO_DISPLAY, item),
                                    PendingIntent.FLAG_CANCEL_CURRENT);
                } else {
                    onClick = PendingIntent.getActivity(this, 0, new Intent(this, LoginActivity.class),
                            PendingIntent.FLAG_CANCEL_CURRENT);
                }

                notification = new OutbidNotification(item, payload.getString(KEY_BID_AMOUNT),
                        getString(R.string.currency_symbol));
                NotificationsActivity.addNotification(notification);
                displayNotification(notification.toString(), onClick);
                return;
            }
        }
    }

    private void displayNotification(String msg, PendingIntent onClick) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.item_hunter_icon_white).setContentTitle("ItemHunter")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

        if (onClick != null) {
            builder.setContentIntent(onClick);
        }
        ((NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID,
                builder.build());
    }
}